Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - "Stuttering" drag when using d3.behavior.drag() and transform

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 "draw" function to update all elements based on the updated model. Additionally, I'm using a translate transform on the containing group element in order to move all the elements associated with the dragged object (I removed the extra elements from the example linked below). This causes the dragged elements to stutter as it's dragged, which gets worse the faster you drag it.

See this stripped-down example on jsFiddle.

Here's the code of the example:

blocks = [
  { x: 0, y: 0 }
];

drag = d3.behavior.drag()
  .origin(Object)
  .on("drag", function(d) {
    d.x = d3.event.x;
    d.y = d3.event.y;
    draw();
  });

svg = d3.select("body")
  .append("svg:svg")
  .attr("width", 600)
  .attr("height", 600);

function draw() {
  g = svg.selectAll("g")
    .data(blocks);

  gEnter = g.enter().append("g");

  g.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; });

  gEnter.append("rect")
    .attr("height", 100)
    .attr("width", 100)
    .call(drag);
}

draw()?;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...