如何在chartjs中悬停时渲染垂直线 [英] How to render a vertical line on hover in chartjs
问题描述
当我将鼠标悬停在chartjs v2中的绘图区域时,我正试图渲染一条垂直线。我有一个基本的工作版本,但我没有想出如何在每次绘制线条时删除线条(旧线条只是粘在一起)。
I'm trying to render a vertical line when hovering over the plot area in chartjs v2. I have a basic working version of it but I haven't figured out how to remove the line each time the line is drawn (the old lines just stick around).
这是一个工作示例 - https://jsfiddle.net/s9gyynxp/5/
Here is a working example - https://jsfiddle.net/s9gyynxp/5/
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
}
});
// Hook into main event handler
var parentEventHandler = Chart.Controller.prototype.eventHandler;
Chart.Controller.prototype.eventHandler = function() {
var ret = parentEventHandler.apply(this, arguments);
// Draw the vertical line here
var eventPosition = Chart.helpers.getRelativePosition(arguments[0], this.chart);
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(eventPosition.x, 30);
this.chart.ctx.strokeStyle = "#ff0000";
this.chart.ctx.lineTo(eventPosition.x, 340);
this.chart.ctx.stroke();
return ret;
};
注意我已经看到了其他解决方案,其中第二个画布层用于图表画布的顶部 - 我不认为这对我来说是一个选项,因为我需要在图表的顶部显示垂直线,但在我将要实现的自定义工具提示下方。
Note I have seen other solutions to this where a second canvas layer is used on top of the chart canvas - I don't think that is an option for me as I need the vertical line to appear on top of the chart, but below a custom tooltip I will be implementing.
感谢任何建议,谢谢!
推荐答案
在绘制线之前添加以下几行
Just add the following lines before you draw your line
...
this.clear();
this.draw();
...
顺便说一句,你的线路一直没有延伸到底部。如果你想让它一直向下拉伸,使用 0
和 this.chart.height
为你的yStart和yEnd 。或者您可以使用y轴刻度来计算刻度的最大和最小像素(请参阅 https://jsfiddle.net/ ombaww9t / )。
By the way, your line doesn't stretch all the way to the bottom. If you want to make it stretch all the way down use 0
and this.chart.height
for your yStart and yEnd. Or you can use the y axis scale to calculate the max and min pixels for the scale (see https://jsfiddle.net/ombaww9t/).
小提琴 - https://jsfiddle.net/56s9av1j/
这篇关于如何在chartjs中悬停时渲染垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!