Dygraphs 在鼠标光标处绘制垂直线

Dygraphs drawing a vertical line at mouse cursor

我想在 Dygraph 图上绘制一条全高垂直线,它遵循光标的精确 x 位置(注意:我希望它在点之间跟随光标,而不仅仅是捕捉到点)

Dygraphs 是否提供允许此操作的回调选项?

作为奖励,是否可以让它与同步播放得很好?

到目前为止,我已尝试将 mousemove 事件侦听器添加到 canvas 以在每个 mousemove 事件上画一条线。这最终只会堵塞情节,因为我无法清除之前绘制的线条,它们只会在每次 mousemove 事件中堆积!

非常感谢任何帮助。

干杯,

P

编辑:我可能取得了一些进展。这是 hacky,但确实提供了光标后一行的视觉效果。但是,它也会覆盖 Dygraphs 的点突出显示行为。我仍然需要高亮点来同步和显示图例中的最近点值。

const plot = new Dygraph(...)

function getCursorPosition(canvas, event) {
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  return [x, y]
}

canvas.addEventListener('mousemove', function(e) {
  // redraw the plot
  const xrange = plot.xAxisRange();
  plot.updateOptions({dateWindow: xrange});

  // add a line
  const [x, y] =getCursorPosition(canvas, e);
  const { height } = canvas;
  ctx.beginPath();
  ctx.moveTo(x, 0);
  ctx.lineTo(x, height);
  ctx.closePath();
  ctx.stroke();
});

看看 hairlines demo, which uses the Dygraph.Plugins.Crosshair 插件。这使用 selectdeselect 事件跟踪突出显示的点并自行绘制细线 canvas.

听起来你已经接近 mousemove 事件了。我不确定 canvas 在您的示例中指的是什么,但它应该是您自己创建并覆盖在测线图上的,就像在 Crosshair 示例中一样。然后你只需要在画线之前清除canvas:

  // add a line
  const [x, y] =getCursorPosition(canvas, e);
  const { height, width } = canvas;
  ctx.clearRect(0, 0, width, height);
  ctx.beginPath();
  ctx.moveTo(x, 0);
  ctx.lineTo(x, height);
  ctx.closePath();
  ctx.stroke();

您可能也对 hairlines demo 感兴趣。您可以左右拖动 "flags"。他们从发际线穿过曲线的任何地方取样。

您需要安装 dygraphs 和 types/dygraphs npm i dygraphs --save npm i @types/dygraphs --save

然后你需要插入这些行来使用插件:

require('./../../../../node_modules/dygraphs/src/extras/synchronizer.js'); declare var Dygraph:any;

根据您的项目更改require 字符串中的路径,您可以在创建图形时使用该插件。来自我正在运行的项目的示例代码:

this.graph = new Dygraph(document.getElementById("graph"), this.data, { legend: 'always', drawPoints: true, animatedZooms: true, showRoller: true, plugins: [ new Dygraph['Plugins'].Crosshair({ direction: "vertical" }), ] })

我在 Angular 8 中使用 Crosshair 插件让它工作。您可以在其他框架中执行类似操作。