gpt4 book ai didi

javascript - 使用D3创建三个圆圈

转载 作者:行者123 更新时间:2023-12-02 18:33:27 24 4
gpt4 key购买 nike

我刚刚开始学习D3。从教程网站上,我找到了以下代码:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">

var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 100)
.attr("height", 100);

sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");});

</script>
</body>
</html>

此代码在屏幕上放置一个圆圈。我想知道有没有办法在屏幕上分别放置三个圆圈?我并不是在谈论将数据绑定(bind)到图表并同时生成多个圆圈,如以下代码所示:

var dataset = [];
var i = 0;
for( i = 0; i < 5; ++i){
dataset.push(Math.round(Math.random() * 100));
}
i = 0.5;
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 500)
.attr("height", 100);

sampleSVG.selectAll("circle")
.data(dataset)
.enter().append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", function(){return (i++) * 80;})
.attr("cy", 40)
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");})
.on("mousedown", animateFirstStep); //animateFirstStep is some transition() function

最佳答案

使用您的 div ID 创建一个数组并循环遍历它。

var tempArray = ["viz", "viz1", "viz2", "viz3"];

检查这个 fiddle :http://jsfiddle.net/EhqVh/

JS

var tempArray = ["viz", "viz1", "viz2", "viz3"];
for (var i = 0; i < tempArray.length; i++) {
var sampleSVG = d3.select("#"+tempArray)
.append("svg")
.attr("width", 100)
.attr("height", 100);

sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("mouseover", function () {
d3.select(this).style("fill", "aliceblue");
})
.on("mouseout", function () {
d3.select(this).style("fill", "white");
});
}

HTML

<div id="viz"></div>

关于javascript - 使用D3创建三个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com