2016-05-14 10 views
4

Ich habe eine Linie in d3 erstellt, die ich umherziehen möchte.Ziehen Sie eine Linie in d3

var line = d3.select("svg") 
       .append("line") 
       .attr("x1",10) 
       .attr("y1",10) 
       .attr("x2",200) 
       .attr("y2",200) 
       .attr("stroke-width",10) 
       .attr("stroke","black") 
       .call(drag); 

Das Problem, das ich jetzt habe, ist, wie die beiden Punkte bewegen (x1, y1) (x2, y2) von der Linie in Bezug auf meine Maus Position, wie ich wahrscheinlich die dragMausPosition als auch benötigen .

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

Ich hoffe, Sie können mir dabei helfen.

Antwort

3

Machen Sie es wie diese in Ihrem Drag-Funktion:

.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(d3.select(this).attr('x1'))+ dx; 
      var y1New = parseFloat(d3.select(this).attr('y1'))+ dy; 
      var x2New = parseFloat(d3.select(this).attr('x2'))+ dx; 
      var y2New = parseFloat(d3.select(this).attr('y2'))+ dy; 
      line.attr("x1",x1New) 
       .attr("y1",y1New) 
       .attr("x2",x2New) 
       .attr("y2",y2New); 
      }).on('dragend', function(){ 
      }); 

Arbeits Code here