简体   繁体   English

在d3中拖动一条线

[英]Drag a Line in d3

I've created a line in d3, which I want to drag around. 我在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);

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. 我现在遇到的问题是如何从相对于我的鼠标位置的线移动点(x1,y1)(x2,y2),因为我可能也需要dragstart鼠标位置。

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(){
           }); 

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(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(){
           }); 

working code here 这里工作代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM