[英]How can I add vertical line and label for each point in Chart.js?
您可以使用插件核心 API直接在canvas
上繪制自己的線條。 它提供了不同的鈎子,可用於執行自定義代碼。 在下面的代碼片段中,我使用afterDraw
鈎子將垂直線繪制到數據集中的各個點。
const data = [65, 0, 80, 81, 56, 85, 40]; new Chart(document.getElementById("myChart"), { type: 'line', plugins: [{ afterDraw: chart => { var ctx = chart.chart.ctx; var xAxis = chart.scales['x-axis-0']; var yAxis = chart.scales['y-axis-0']; xAxis.ticks.forEach((value, index) => { var x = xAxis.getPixelForTick(index); var yTop = yAxis.getPixelForValue(data[index]); ctx.save(); ctx.strokeStyle = '#aaaaaa'; ctx.beginPath(); ctx.moveTo(x, yAxis.bottom); ctx.lineTo(x, yTop); ctx.stroke(); ctx.restore(); }); } }], data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", data: data, fill: false }] }, options: { legend: { display: false }, scales: { yAxes: [{ gridLines: { display: false } }], xAxes: [{ gridLines: { display: false } }] } } });
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js'></script> <div style="width: 75%"> <canvas id="myChart" height="90"></canvas> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.