当我点击鼠标时,我想要弹出4个彩色圆圈;但是,只有最后一个紫色圆圈(var circle4)是我点击鼠标后出现的唯一一个。使用方法(shape.on(“click”,function()...),我可以通过单击鼠标来显示一个圆圈。我试图同时调出所有这些,但我只是继续得到最后一个圆圈。我认为将方法应用到所有圆圈都可以。这是我的代码:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>D3 Circle Split</title>
<script type = "text/javascript" src = "js/d3.v3.js"></script>
</head>
<body>
<script type = "text/javascript">
var h = 2000;
var w = 2000;
var xGrid = 300;
var yGrid = 300;
var radius = 300;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var shape = svg.append("circle")
.attr("cx", xGrid)
.attr("cy", yGrid)
.attr("r", radius)
.style("fill", "yellow")
shape.on("click", function(){
var circle1 = svg.append("circle")
.attr("cx", xGrid - radius/2)
.attr("cy", yGrid - radius/2)
.attr("r", radius/2)
.style("fill", "red")
});
shape.on("click", function(){
var circle2 = svg.append("circle")
.attr("cx", xGrid + radius/2)
.attr("cy", yGrid - radius/2)
.attr("r", radius/2)
.style("fill", "blue")
});
shape.on("click", function(){
var circle3 = svg.append("circle")
.attr("cx", xGrid - radius/2)
.attr("cy", yGrid + radius/2)
.attr("r", radius/2)
.style("fill", "green")
});
shape.on("click", function(){
var circle4 = svg.append("circle")
.attr("cx", xGrid + radius/2)
.attr("cy", yGrid + radius/2)
.attr("r", radius/2)
.style("fill", "purple")
});
</script>
</body>
</html>
答案 0 :(得分:1)
你可以一次完成所有4个圈子。另外,请与@Ole Suffaus一起回答;
shape.on('click', function() {
var circles = svg.selectAll('circle')
.data(['red', 'blue', 'green', 'purple'])
.enter().append('circle')
.attr('cx', function(d, i) {
return xGrid - radius / 2 + i * 10;
})
.attr('cy', function(d, i) {
return yGrid - radius / 2 + i * 10;
})
.attr('r', radius / 2)
.style('fill', function(d) {
return d;
});
});
答案 1 :(得分:0)
您的所有圈子似乎都具有相同的尺寸和坐标...因此,只有最后一个圈子可见,因为它们位于彼此之上。
试试这个:
<script>
var h = 2000;
var w = 2000;
var xGrid = 300;
var yGrid = 300;
var radius = 300;
var svg = d3.select("body")
.append("svg").attr("width",w).attr("height",h);
var shape = svg.append("circle")
.attr("cx",xGrid).attr("cy",yGrid).attr("r",radius).style("fill","yellow");
shape.on("click", function(){
var circle1 = svg.append("circle")
.attr("cx", xGrid-radius/2)
.attr("cy", yGrid-radius/2)
.attr("r", (radius/2)+30)
.style("fill", "red");
var circle2 = svg.append("circle")
.attr("cx", (xGrid-radius/2)+10)
.attr("cy", (xGrid-radius/2)+10)
.attr("r", (radius/2)+20)
.style("fill", "blue");
var circle3 = svg.append("circle")
.attr("cx", (xGrid-radius/2)+20)
.attr("cy", (xGrid-radius/2)+20)
.attr("r", (radius/2)+10)
.style("fill", "green");
var circle4 = svg.append("circle")
.attr("cx", (xGrid-radius/2)+30)
.attr("cy", (xGrid-radius/2)+30)
.attr("r", radius/2)
.style("fill", "purple");
});
</script>