【发布时间】:2017-12-04 18:07:42
【问题描述】:
我使用的是 Chart.js 2.6,并且我已经实现了 HorizontalLine 插件来在我的条形图上显示平均值。它工作正常,但是当工具提示显示在它与线相交的位置时,它会被水平线本身部分覆盖。我试图弄清楚如何使工具提示在水平线上方绘制。
我了解工具提示是画布元素的一部分,因此没有 z-index 属性。我怎样才能做到这一点?
这是我用于水平线插件的内容。
var horizonalLinePlugin = {
afterDraw: function(chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index, line, style, width;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
style = (line.style) ? line.style : "rgba(169,169,169, .6)";
yValue = (line.y) ? yScale.getPixelForValue(line.y) : 0 ;
ctx.lineWidth = (line.width) ? line.width : 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(chartInstance.chartArea.left, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
}
}
};
Chart.pluginService.register(horizonalLinePlugin);
...然后我使用以下命令将其添加到条形图选项中
options: {
...standard option stuff...
"horizontalLine": [{
"y": averageValue,
"style" : colorOfTheLine
}]
}
这会生成如下图所示的图表。
..但是,当您将鼠标悬停在图表的某个部分上以显示工具提示时,并且工具提示位于水平线的路径中,则会导致以下问题。
【问题讨论】:
-
如果您可以从 chart.js 文件中干扰画布,也许可以使用此解决方案。 stackoverflow.com/questions/9165766/html5-canvas-set-z-index
-
决定只使用解决了整个问题的 DOM 工具提示。不过谢谢!
标签: javascript jquery chart.js chart.js2