首页 > 解决方案 > 使用 Chart.js 添加水平十字准线

问题描述

我正在使用 Chart.js,并且一直在寻找一种在我的图表中添加水平注释/十字准线的方法。

How to create a horizontal crosshair that changes its position based on the cursor movement using Chart.js?

JSFiddle for my application :- https://jsfiddle.net/codeandcloud/vz4qhqpw/

I have seen that in canvas.js this Functionality works but i want to use chart.js only ( Canvas Js Jsfiddle https://jsfiddle.net/uwfom5Le/ )`enter code here`

标签: chart.js

解决方案


尝试

  const options = {
    hover: {
      intersect: false
    },
    onHover: function(this: Chart, event: MouseEvent, activeElements: Array<object>): any {
      if (activeElements.length) {
        const activePoint = activeElements[0] as any;
        const ctx = this.ctx;
        if (!ctx) {
          return;
        }
        const x = activePoint._view.x;
        const y = activePoint._view.y;
        const leftX = this.chartArea.left;
        const topY = this.chartArea.top;
        const RightX = this.chartArea.right;
        const bottomY = this.chartArea.bottom;
        ctx.beginPath();
        ctx.moveTo(x, topY);
        ctx.lineTo(x, bottomY);
        ctx.moveTo(leftX, y);
        ctx.lineTo(RightX, y);
        ctx.lineWidth = 1;
        ctx.strokeStyle = "#C2C7CC";
        ctx.stroke();
        ctx.closePath();
      }
    },
   //...
}

推荐阅读