5

I'm experiencing 'stutter' with the D3 drag behavior.

Seems to be a similar problem to "Stuttering" drag when using d3.behavior.drag() and transform

However the solution does not seem to work for the zoom behavior.

Here is an example of the issue: (try dragging the rectangle) http://jsfiddle.net/EMNGq/109/

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

var translate_var = [0,0];

zoom_var = d3.behavior.zoom()
  .on("zoom", 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")
    .call(zoom_var);

  g.attr("transform", function(d) { return "translate("+translate_var[0]+","+translate_var[1]+")"; });

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

draw()
Community
  • 1
  • 1
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286

1 Answers1

7

You zoom in or drag the element, but then translate the same element. Because the translation is relative, it results in this stuttering.

As stated in the documentation for Zoom Behavior:

This behavior automatically creates event listeners to handle zooming and panning gestures on a container element. Both mouse and touch events are supported.

Contrast it to the documentation for Drag Behavior:

This behavior automatically creates event listeners to handle drag gestures on an element. Both mouse events and touch events are supported.

Your solution is inverse to the similar question. Call your zoom function on the container.

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

Here's the demo.

You might also be interested in the actual zoom. To do that simply add the scale to your transform rule. Here's the demo with zoom enabled.

Oleg
  • 9,341
  • 2
  • 43
  • 58