[英]Triggering ChartJS Point Hover from elsewhere on the page
我正在使用 chartjs 為每個元素生成一個帶有點的折線圖。 目前,將鼠標懸停在圖表上的某個點上會觸發該數據點的工具提示。 是否可以從頁面上的其他位置觸發此鼠標懸停事件(以及生成的工具提示)? (更具體地說,將鼠標懸停在表格中的一行應該會觸發圖表上的相應數據點)
function render_graph(input) {
// setup block
const data = {
datasets: [{
type: 'line',
parsing: {
yAxisKey: 'Average Pace',
xAxisKey: 'Date',
},
label: '# of Votes',
radius: 3,
data: arr,
backgroundColor: 'red',
borderColor: 'red',
borderWidth: 1,
label: "Pace",
}]
}
// config block
const config = {
data,
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'year'
}
},
y: {
suggestedMin: 360,
suggestedMax: 900,
ticks: {
stepSize: 30,
padding: 2,
callback: function(value, index, ticks) {
minutes = Math.floor(value / 60);
seconds = value % 60;
if (seconds == 0) {
seconds = "00";
}
x = minutes + ':' + seconds;
return x;
}
},
}
},
}
};
// render / init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
return myChart;
}
您可以使用setActiveElements
工具提示/圖表 API。 這是一個片段代碼來展示它是如何工作的。
const ctx = document.getElementById("myChart"); const myChart = new Chart(ctx, { type: 'line', data: { labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'user 1 online', data: [50, 35, 45, 47, 0, 3, 27], backgroundColor: 'rgba(40, 139, 170, 1)', borderColor: 'rgb(40, 139, 170)', pointHoverBackgroundColor: 'yellow', pointHoverRadius: 20 }] } }); document.getElementById('chart').addEventListener('click', function() { if (myChart.getActiveElements().length > 0) { myChart.setActiveElements([]); } else { myChart.setActiveElements([ { datasetIndex: 0, index: 1, }, { datasetIndex: 0, index: 3, } ]); } myChart.update(); }); document.getElementById('tooltip').addEventListener('click', function() { const tooltip = myChart.tooltip; if (tooltip.getActiveElements().length > 0) { tooltip.setActiveElements([], {x: 0, y: 0}); } else { const chartArea = myChart.chartArea; tooltip.setActiveElements([ { datasetIndex: 0, index: 1 } ], { x: (chartArea.left + chartArea.right) / 2, y: (chartArea.top + chartArea.bottom) / 2, }); } myChart.update(); });
.myChartDiv { max-width: 600px; max-height: 400px; }
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script> <html> <body> <div class="myChartDiv"> <canvas id="myChart" width="600" height="400"/> </div> <button id="chart">Chart active element</button> <button id="tooltip">Tooltip active element</button> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.