Tengo pocos puntos, por ejemplo. ( { x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 } ). Chart.js puede dibujar un gráfico para mí basándose en estos puntos. ¿Hay alguna forma de leer el valor y de, por ejemplo. 13 usando la tabla dibujada? Estoy usando chart.js 2.9.3 (no puedo cambiarlo) y vue.js. ¡Gracias por cualquier consejo!
Esto se puede hacer con la siguiente función:
function valueAt(x) { let xScale = chart.scales['x-axis-0']; let yScale = chart.scales['y-axis-0']; let data = chart.data.datasets[0].data; let index = data.findIndex(o => ox >= x); let prev = data[index - 1]; let next = data[index]; if (prev && next) { let slope = (next.y - prev.y) / (next.x - prev.x); return prev.y + (x - prev.x) * slope; } }La mayoría del código se copia de
interpolate.jsdel excelentechartjs-plugin-crosshair.
Eche un vistazo al código ejecutable a continuación y vea cómo funciona:
const chart = new Chart("chart", { type: 'line', data: { datasets: [{ label: '', data: [{ x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }], type: 'line', borderColor: 'red', fill: false, }], }, options: { responsive: false, scales: { xAxes: [{ type: 'linear' }] } } }); function valueAt(x) { let xScale = chart.scales['x-axis-0']; let yScale = chart.scales['y-axis-0']; let data = chart.data.datasets[0].data; let index = data.findIndex(o => ox >= x); let prev = data[index - 1]; let next = data[index]; if (prev && next) { let slope = (next.y - prev.y) / (next.x - prev.x); return prev.y + (x - prev.x) * slope; } } let x = 13; let y = valueAt(x); console.log('x: ' + x + ' -> y: ' + y); <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="chart" height="200"></canvas>