user3701098 user3701098 - 9 months ago 85
Javascript Question

Drag a Line in d3

I've created a line in d3, which I want to drag around.

var line ="svg")

The problem I have right now, is how to move both Points (x1,y1) (x2,y2) from the line relative to my mouse position, as I probably will need the dragstart mouse position as well.

let drag = d3.behavior.drag()
.on('dragstart', null)
.on('drag', function(){
// move circle
let x1New ='x1')+ ???;
let y1New ='y1')+ ???;
let x2New ='x2')+ ???;
let y2New ='y2')+ ???;
.on('dragend', function(){

I hope you can help me with that.


Do it like this inside your drag function:

.on('drag', function(d){
             // move circle
             var dx = d3.event.dx;//this will give the delta x moved by drag
             var dy = d3.event.dy;//this will give the delta y moved by drag
             var x1New = parseFloat('x1'))+ dx;
             var y1New = parseFloat('y1'))+ dy;
             var x2New = parseFloat('x2'))+ dx;
             var y2New = parseFloat('y2'))+ dy;
             }).on('dragend', function(){

working code here