S.Dan
S.Dan

Reputation: 1920

How to make the transform:translate-drag function of d3 more smooth?

In this JSFiddle I have implemented elements in svg. I want the group of elements to be draggable and I have tried it with d3.drag and using transform:translate. The drag is not smooth. It flickers and jumps here and there.

What is the reason behind it and how can it be overcome?

The drag function is as follows:

var dragcontainer = d3.drag()
  .on("start", function() {})
  .on("drag", function(d, i) {
    var x = d3.event.x;
    var y = d3.event.y;
      d3.select(this.parentNode.parentNode).attr("transform", "translate(" + x + "," + y + ")");
  })
  .on("end", function() {});

Upvotes: 4

Views: 2777

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

Instead of attaching the drag listener to the foreign object div:

d3.select("#input-container-div").call(dragcontainer);

Add it to the svg group like this:

d3.select(d3.select("#input-container-div").node().parentNode.parentNode).call(dragcontainer);

Secondly instead of using d3.event.x/d3.event.y

var x = d3.event.x;
var y = d3.event.y;

Use dx and dy to get the mouse movement difference and store its for future drag.

Like this:

  this.x = this.x || 0;//reset if not there
  this.y = this.y || 0;

    this.x += d3.event.dx;
    this.y += d3.event.dy;
  d3.select(this).attr("transform", "translate(" + this.x + "," + this.y + ")");

working code here

Upvotes: 6

Related Questions