使用Chart.js添加水平十字线

时间:2019-06-27 14:32:13

标签: 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`

1 个答案:

答案 0 :(得分:0)

尝试

  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();
      }
    },
   //...
}