使用chart.js将鼠标悬停在图表上时移动垂直线

yrdbyhpb  于 2022-11-23  发布在  Chart.js
关注(0)|答案(3)|浏览(190)

我一直在尝试添加一条垂直线,当鼠标悬停在图表上时,它会显示一个工具提示,但是我使用的是chart.js2.6,1.x的语法似乎已经过时了。
下面的代码可以在for 1.x下运行
第一个
External link
有人知道如何让它工作吗for 2.6

hwamh0ep

hwamh0ep1#

ChartJS 2.6.0的解决方案

*********)

Chart.defaults.LineWithLine = Chart.defaults.line;
Chart.controllers.LineWithLine = Chart.controllers.line.extend({
    draw: function(ease) {
        Chart.controllers.line.prototype.draw.call(this, ease);

        if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
            var activePoint = this.chart.tooltip._active[0],
                ctx = this.chart.ctx,
                x = activePoint.tooltipPosition().x,
                topY = this.chart.legend.bottom,
                bottomY = this.chart.chartArea.bottom;

            // draw line
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(x, topY);
            ctx.lineTo(x, bottomY);
            ctx.lineWidth = 2;
            ctx.strokeStyle = '#07C';
            ctx.stroke();
            ctx.restore();
        }
    }
});

还需要为工具提示设置**intersect: false**。


第一次

3zwtqj6y

3zwtqj6y2#

试试看:

var ctx = this.$refs.canvas.getContext("2d");
// new Chart(ctx, config);
var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function() {
    originalLineDraw.apply(this, arguments);

    var chart = this.chart;
    var ctx = chart.chart.ctx;

if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
    var activePoint = this.chart.tooltip._active[0];
    var ctx = this.chart.ctx;
    var x = activePoint.tooltipPosition().x;
    var topY = this.chart.scales['y-axis-0'].top;
    var bottomY = this.chart.scales['y-axis-0'].bottom;

    // draw line
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(x, topY);
    ctx.lineTo(x, bottomY);
    ctx.lineWidth = 0.5;
    ctx.strokeStyle = '#eeeeee';
    ctx.stroke();
    ctx.restore();
}
}});

这绝对会帮到你的。

cvxl0en2

cvxl0en23#

这个问题已经有五年的历史了。现在,我们可以使用plugins和钩子调用来实现这个问题。在这个例子中,beforeTooltipDraw可以捕获tooltip.caretX。我们也可以使用内置的interaction option来实现这个问题。
此实现适用于ChartJS的3.x和4.0.1版
第一个

相关问题