抱歉,如果我的问题措辞不好。我是初学者,不知道事物的正确标签。
我正在使用 d3.js 制作日本 map ,并想为每个都道府县分配一种颜色。每个都道府县都有自己的 svg。我有一个要使用的颜色的十六进制值的数组,基本上想编写一个函数,将数组的第一种颜色分配给第一个 svg 的“填充”属性,将第二个颜色分配给第二个,依此类推。由于都道府县太多,颜色有时必须重复。我真的很难概念化如何解决这个问题,并且希望得到任何帮助!我的代码如下。我认为代码应该放在 javascript 的底部,我有 ?评论。
此外,此基础来自 Mike Bostock 的“让我们制作 map ”教程(如果有帮助的话)。
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960;
var height = 1160;
/* list of colors to iterate thru for prefecture color */
var colors = ["#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3",
"#fdb462", "#b3de69", "#fccde5", "#d9d9d9"];
var projection = d3.geo.mercator()
.center([138.3, 39.2])
.scale(1500);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("height", height)
.attr("width", width);
/* draws the map. try to make a loop in here which uses the data id of
the prefectures to uses the color list above to differentiate pref*/
d3.json("japanv2.json", function(error, japan) {
svg.selectAll(".prefecture")
.data(topojson.feature(japan, japan.objects.prefectures).features)
.enter().append("path")
.attr("class", function (d) { return "prefecture " + d.id; })
.attr("d", path)
/*?*/ .attr("fill",
}
});
</script>
</body>
</html>
最佳答案
将其放入属性中:
.attr("fill", function(d,i){
return colors[i%colors.length]
});
这段代码有什么作用?
首先,function(d,i)
中的 i
返回每个路径的索引。所以,如果你这样做:
.attr("fill", function(d,i){
console.log(i);
return colors[i%colors.length];
});
您将在控制台上看到一堆数字。假设您有 200 条路径,i
的范围为 0 到 199。
现在是模运算符:
x % y
它返回 remainder该部门的。因此,假设您的 colors
是一个包含 9 种颜色的数组,则:
i % colors.length
将返回此序列:
0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1 etc
您可以使用它来获取颜色
值。
PS:在一张 map 中,任何 map ,我们只需要 4 colours以避免任何两个具有相同颜色的区域有共同的边框! (难以置信,我知道......)
关于javascript - 如何一遍又一遍地迭代数组,同时将其每个值分配给 DOM 中的所有 svgs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38449461/