我正在使用Chart.js 2.6并且我已经实现了horizontalLine插件以在条形图上显示平均值。它工作正常,但是当工具提示显示在与线相交的点上时,它部分被水平线本身覆盖。我试图弄清楚如何使工具提示在水平线上绘制。
我理解工具提示是canvas元素的一部分,因此没有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
}]
}
生成一个类似下图的图表。
..但是,当您将鼠标悬停在图表的某个部分上以显示工具提示时,并且工具提示位于水平线的路径中时,会导致出现以下问题。
答案 0 :(得分:4)
将您的插件附加到 afterDatasetDraw
挂钩,而不是 afterDraw
。这将使工具提示之前绘制水平线。
var horizonalLinePlugin = {
afterDatasetDraw: 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);
new Chart(canvas, {
type: 'bar',
data: {
labels: ["January", "February"],
datasets: [{
label: "Dataset 1",
data: [80, 50]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
horizontalLine: [{
y: 50,
style: 'red'
}]
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
&#13;