1

I wanted to show a vertical line that follows my mouse on my chartjs canvas and the following codes does what I one except one thing, it will stop updating once the tooltips fades out (when there is no data intersects with my cursor). I know it has something to do with rendering but I do not know how and what variable I have to manipulate with.

I can force the animation playing non-stop by setting my animation as timed loop but I don't think this is a proper solution. This will also consume more resources since I need only my lines to be updating constantly not the whole graph.

The function is implemented with inline plugin. Please have a look, thank you!

     let canvas = document.getElementById('myChart')

      function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
        };
      }

      let mousePosX;

      canvas.addEventListener('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        mousePosX = mousePos.x;
      }, false);

      const config = {
        type: 'scatter',
        plugins: [
          {
            afterDraw(chart) { 
                let x = mousePosX;         
                let yAxis = chart.scales.y;
                let ctx = chart.ctx;
                ctx.save();
                ctx.beginPath();
                ctx.moveTo(x, yAxis.top);
                ctx.lineTo(x, yAxis.bottom);
                ctx.lineWidth = 1;
                ctx.strokeStyle = 'rgba(0, 0, 255, 0.4)';
                ctx.stroke();
                ctx.restore();
            },
          }
        ],
        .....
microCuts
  • 21
  • 1
  • 2
  • why not just use the [crosshair plugin?](https://www.npmjs.com/package/chartjs-plugin-crosshair) – Jesper Sep 16 '21 at 09:30
  • My intention is to draw a true crosshair, both vertical and horizontal the same time. Unless i missed some thing..i don't see there is a way to do that with that plugin. – microCuts Sep 16 '21 at 12:14
  • Ah, okay. You could take some inspiration from the project if you don't get any answers. I would also suggest posting more code. I can only guess that chart.js also using the mouse move event of the canvas, is messing with your mouse move event. You could try disabling that event, or adding your event under chart.js options, but this is just a guess. – Jesper Sep 16 '21 at 13:21
  • Pretty sure it has something to do with the animation. As soon as there is no animations on the chart, my crosshair will stop working (updating). Will post the full code when I sort it out. Thanks. – microCuts Sep 16 '21 at 14:59

0 Answers0