简体   繁体   中英

Drag multiple items inside another item in d3

I have three circles in a rectangle. Whenever I drag the rectangle all three circles should move with my rectangle. However, whenever I move one of the circles that specific circle should move. Other circles and rectangle should not move.

在此处输入图片说明

I have no idea where should I start from. I know how to drag a single circle or multiple circles but no idea how to do this. Any idea?

Try this code.

 var w = 200, h = 200; var drag = d3.behavior.drag().on('dragstart',function(){ d3.event.sourceEvent.stopPropagation(); }).on("drag", function() { var x = d3.event.x, y = d3.event.y; if(this.tagName=='circle'){ if(x<=w-10 && x>=10 && y<=h-10 && y>=10) d3.select(this).attr("cx",x).attr("cy",y); }else d3.select(this).attr("transform","translate("+x+","+y+")"); });; var container = d3.select('body').append("svg").attr("width",1200).attr("height",600); var group = container.append("g") var rect = group.append("rect").attr("width",w).attr("height",h).attr("x",10).attr("yx",10); var circle1 = group.append("circle").attr("cx",50).attr("cy",50).attr("r",10).style("fill","red"); var circle2 = group.append("circle").attr("cx",100).attr("cy",70).attr("r",10).style("fill","red"); circle1.call(drag); circle2.call(drag); group.call(drag);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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