Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {});
like image 625
S.Dan Avatar asked Sep 05 '25 03:09

S.Dan


1 Answers

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

like image 162
Cyril Cherian Avatar answered Sep 09 '25 20:09

Cyril Cherian