如何在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.
任何建议都非常感谢,谢谢!
Any suggestions are appreciated, thanks!
推荐答案
在画线之前添加以下几行
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/
相关文章