我喜歡兩個圓的方法,但我會將它們分組在g
元素中。拖動即可工作的g
元素和第二圈是簡單地擴大g
:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
</head>
<body>
<script>
var boxWidth = 600;
var boxHeight = 400;
var box = d3.select('body')
.append('svg')
.attr('class', 'box')
.attr('width', boxWidth)
.attr('height', boxHeight);
var drag = d3.behavior.drag()
.on('dragstart', function() {
circle.style('fill', 'red');
})
.on('drag', function() {
d3.select(this)
.attr('transform', function(d) {
return "translate(" + d3.event.x + "," + d3.event.y + ")";
});
})
.on('dragend', function() {
circle.style('fill', 'black');
});
var dragCircles = box.selectAll('.draggableCircle')
.data([{
x: (boxWidth/2),
y: (boxHeight/2),
r: 25
}])
.enter()
.append('g')
.attr('class', 'draggableCircle')
.attr('transform', function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
.style('cursor', 'crosshair')
.call(drag);
dragCircles.append("circle")
.attr('r', function(d){
return d.r * 3;
})
.style('fill', 'transparent');
var circle = dragCircles.append("circle")
.attr('r', function(d) {
return d.r;
})
.style('fill', 'black');
</script>
</body>
</html>
另外,我會打擾你一個問題 - 如果有多個圈,我代碼使用d3.select(this)給出了父對象「g」,那麼如何引用並從那裏更改可見圓?我可以將它作爲父對象的子項引用嗎?以及如何? –
@CindyAlmighty'this.children'是'g'裏面圈子的集合,所以'd3.select(this.children [1])'是第二個可見圓的選擇。 – Mark