首页 > 解决方案 > 鼠标指针与十字准线指针不同步。在 D3 v6 中

问题描述

使用 D3 v5.16 时。鼠标指针通过使用 . 与我的十字准线指针同步d3.mouse。它们完全对齐移动。

var coordinates =  d3.mouse(this);

将 D3 v5.16 升级到 D3 v6.2时,鼠标指针不再与十字准线指针同步,它们之间存在偏移。我正在使用d3.pointer代替d3.mouse来获取鼠标的位置,但这并没有给出确切的坐标。

var coordinates =  d3.pointer(event,this);

示例代码

const generator = fc.randomFinancial()
  .filter(fc.randomSkipWeekends);

const data = generator(100);
var annoationData = [{ x: data[50].date, y: data[50].high }];
const dateFormat1 = d3.timeFormat("%d/%m/%y");
data.forEach(d => {
  d.date = new Date(d.date);
  d.high = Number(d.high);
  d.close = Number(d.close);
  d.open = Number(d.open);

  const xExtent = fc.extentDate()
    .accessors([d => d.date])

  const xScale = fc.scaleDiscontinuous(d3.scaleTime())
    .discontinuityProvider(fc.discontinuitySkipWeekends())
    .domain(xExtent(data))
    .nice()

  const yScale = d3
    .scaleLinear()
    .domain(fc.extentLinear().accessors([d => d.high, d => d.low, d => d.open, d => d.close])(data))
    .nice()

  const line = fc.seriesSvgLine()
    .crossValue(d => d.date)
    .mainValue(d => d.high)

  const crosshair = fc
    .annotationSvgCrosshair()
    .x(d => xScale(d.x))
    .y(d => yScale(d.y))
    .xLabel(d => dateFormat1(d.x))
    .yLabel(d => d.y.toLocaleString())

    .decorate(selection => {
      selection
        .enter()
        .attr("strokeStyle", "blue")
        .style("stroke-dasharray", ("10,1"))
        .attr("stroke-width", 1)

      selection
        .select('.top-handle')
        .append('text')
      selection.select('.top-handle text').text(d => dateFormat1(d.x));

    })

  var series = fc
    .seriesSvgMulti()
    .series([line, crosshair])
    .mapping((data, index, series) => {
      switch (series[index]) {
        case crosshair:
          return annoationData;
        default:
          return data;
      }
    });

  const chart = fc
    .chartCartesian(xScale, yScale)
    .xLabel('Date')
    .yLabel('High')
    .xTicks(10)
    .xTickFormat(dateFormat1)
    .yTickFormat(d3.format("~s"))
    .yOrient('right')
    .svgPlotArea(series)
    .decorate(sel => {
      sel.enter()
        .select('.plot-area')
        .on('mousemove', event => {
          var cordinates = d3.pointer(event, this)
          var clientX = cordinates[0];
          var clientY = cordinates[1];
          annoationData[0] = { x: xScale.invert(clientX), y: yScale.invert(clientY) };
          render();
        })
    });

  const render = () => {
    d3.select('#chart')
      .datum(data)
      .call(chart)
  };

  render();
});

标签: d3.jsd3fc

解决方案


推荐阅读