“Stuttering” drag when using d3.behavior.drag() and transform

前端 未结 3 445
陌清茗
陌清茗 2020-12-09 04:01

I\'m trying to use d3.js\'s d3.behavior.drag() drag event to update my data model (without setting the element position immediately), then run my \

3条回答
  •  庸人自扰
    2020-12-09 04:15

    You are calling drag on the rect element, but you're transforming its parent: the g element.

    The problem is that the drag component uses the mouse location relative to the parent to determine the new d3.event.x and d3.event.y. So, if you move (i.e. transform) the parent while the user drags, things get messed up.

    The solution is to call drag on the same element that you are moving around; in this case the g element:

    function draw() {
      g = svg.selectAll("g")
        .data(blocks);
    
      gEnter = g.enter().append("g")
        .call(drag);
    
      g.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; });
    
      gEnter.append("rect")
        .attr("height", 100)
        .attr("width", 100);
    }
    

    See corrected Fiddle: http://jsfiddle.net/EMNGq/14/

提交回复
热议问题