簡體   English   中英

ChartJS:在 hover 上的兩個數據點之間畫線

[英]ChartJS: Draw line between two data points on hover

在此處輸入圖像描述

大家好,我已經創建了圖像中顯示的圖表。

有誰知道在嘗試對任一數據(紅線)進行 hover 時如何在相同索引的數據集之間畫一條線。

我在 VueJS 組件上使用 ChartJS

插件核心 API提供了一系列可用於執行自定義代碼的鈎子。 您可以使用CanvasRenderingContext2D.stroke()直接在canvas上畫線。

在下面的代碼片段中,我使用afterDraw鈎子並畫線,以防工具提示以其他方式顯示。 請參閱vue-chart.js文檔中的addPlugin以了解如何在Vue.js中添加此類內聯插件。

 var chart = new Chart('canvas', { type: 'line', plugins: [{ afterDraw: chart => { if (chart.tooltip._active && chart.tooltip._active.length) { const ctx = chart.ctx; ctx.save(); const activePoint = chart.tooltip._active[0]; const x = activePoint.tooltipPosition().x; const yAxis = chart.scales['y-axis-0']; const value1 = chart.data.datasets[0].data[activePoint._index]; const value2 = chart.data.datasets[1].data[activePoint._index]; const y1 = yAxis.getPixelForValue(value1); const y2 = yAxis.getPixelForValue(value2); ctx.beginPath(); ctx.moveTo(x, y1); ctx.lineTo(x, y2); ctx.lineWidth = 2; ctx.strokeStyle = 'green'; ctx.stroke(); ctx.restore(); } } }], data: { labels: ['A', 'B', 'C', 'D', 'E', 'F'], datasets: [{ data: [13, 10, 12, 13, 9, 12], backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgb(255, 99, 132)', fill: false }, { data: [10, 7, 9, 10, 6, 9], backgroundColor: 'rgba(255, 159, 64, 0.2)', borderColor: 'rgb(255, 159, 64)' } ] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> <canvas id="canvas" height="90"></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM