2015-10-08 88 views
2

我在矩形中有三個圓圈。每當我拖動矩形時,所有三個圓圈都應該隨矩形一起移動。但是,每當我移動特定圓圈應該移動的某個圓圈時。其他圓圈和矩形不應該移動。在d3中拖放另一個項目中的多個項目

enter image description here

我不知道在哪裏應該從我做起。我知道如何拖動一個圈子或多個圈子,但不知道如何做到這一點。任何想法?

回答

2

試試看看這個代碼。

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>

相關問題