alexchenco alexchenco - 1 year ago 43
Javascript Question

Initial "jumpy" dragging behavior

The following code creates a background and a rectangle. The rectangle can be dragged:

var p = {
x: 0,
y: 0
}

var width = 400
var height = 400

var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)

svg.append('rect')
.attr('class', 'bg')
.attr('width', width)
.attr('height', height)

var drag = d3.behavior.drag()
.on('drag', dragmove)

svg.append('rect')
.attr('class', 'btn')
.attr('width', 100)
.attr('height', 50)
.attr('transform', 'translate(' + p.x + ',' + p.y + ')')
.call(drag)

function dragmove (d) {
var x = d3.event.x
var y = d3.event.y
d3.select(this)
.attr('transform', 'translate(' + x + ',' + y + ')')
}


The dragging event works, but there's an initial "jump" each time I drag the object (e.g the rectangle starts on the left of the cursor and then suddenly jumps to the right).

You can see it here: https://jsfiddle.net/alexcheninfo/5rnv7ww5/

What is causing it and how to prevent it (make the rectangle being dragged smoothly from the beginning)?

Answer Source

It should be this way:

//get the translate on the dragged rectangle
var translate = d3.transform(d3.select(this).attr("transform")).translate;
//to that add the mouse move deltax 
                x = d3.event.dx + translate[0],
                y = d3.event.dy + translate[1];

working code here

when you do

var x = d3.event.x
  var y = d3.event.y
  d3.select(this)
    .attr('transform', 'translate(' + x + ',' + y + ')')

It will translate the rectangle to the mouse position thus the jump.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download