如何解决奇怪的拖拽行为?

时间:2017-01-26 20:16:01

标签: d3.js

以下是简化代码:

this.x.domain(d3.extent(data, d => d.x));
this.y.domain([ 0, d3.max(data, d => d.y) ]);

svg.selectAll('circle')
           .data(data)
           .enter()
           .append("circle")
           .attr('cx', d => this.x(d.x))
           .attr('cy', d => this.y(d.y))
           .attr('r', 4)
           .attr('class', 'circle')
           .style("fill", "white")
           .style("stroke", "steelblue")
           .style("pointer-events", "all")
           .style("stroke-width", "2px")
           .call(d3.drag()
                   .on("start", dragStarted)
                   .on("drag", dragged)
                   .on("end", dragended));

function dragStarted( d ) {
    d3.select(this).raise().classed("active", true);
}

function dragged( e ) {

            let yLocation = d3.event.y;
            e.y           = y.invert(d3.mouse(this)[ 1 ]);

            console.log(e);
            d3.select(this)
              .attr("cy", yLocation);

            // update(data);

    }

问题是当我第一次拖动圆圈时,圆圈位于图表的上部。圈子刚刚上升。如何确保拖动从圆圈的原始位置开始而没有移位?

1 个答案:

答案 0 :(得分:0)

我通过将其添加到d3.drag()

来解决了这个问题
d3.drag().subject(function () {
     let t = d3.select(this);
      return { x: t.attr("cx"), y: t.attr("cy") 
};

这将在没有跳跃的情况下修复原始位置。

相关问题