我有一个在 inkscape 中制作的 SVG,现在我想根据数据集值在 svg 中填充颜色,但不知怎的,我什至无法显示简单的填充。不知道如何实现这一点。
var svg_0 = d3.xml("continents_clean.svg", "image/svg+xml", function(xml) {
var importedNode = document.importNode(xml.documentElement, true);
d3.select("#viz").node().appendChild(importedNode);
var dataset;
function checkIt(data){
for (var i in data) {
var data_clean;
data_clean = data[i].Total
dataset = data_clean
fillSvg();
}
}
d3.json("data.json", checkIt);
function fillSvg(){
var svg = d3.select("#level_0")
.selectAll("path")
.data(dataset)
.enter()
.append("path")
.style("fill", "purple");
console.log(svg)
}
});
数据
[{
"Continent":"Asia.Oceania",
"Country_Names":"Yemen",
"Total":20
},
{
"Continent":"Misc",
"Country_Names":"World marine bunkers",
"Total":602.2
},
{
"Continent":"Misc",
"Country_Names":"World aviation bunkers",
"Total":477.8
}
]
最佳答案
我误解了你的意思,所以请忽略我之前写的关于 .enter().append('path') 的内容。
调用您选择的每个方法,并确保选择您的路径并且它们对应于正确的 json 数据对象。如果 console.log 的回调根本没有被触发,这意味着您实际上没有选择路径(因为查询字符串错误)或者您的数据集数组没有 json 对象。
d3.select("#level_0")
.selectAll("path")
.data(dataset)
.each(function(d, i){
console.log(this, d, i); // <-- make sure that your data corresponds to your dom elements
})
.style('fill', function(d){
return 'purple'; //<-- here you can set the color depending on values of d
});
如果您传递给每个函数的回调被调用,但颜色未更改,请转到开发人员工具的“元素”面板并检查 fill
是否实际设置为紫色。
尝试更改笔划颜色 .style('笔划', 'purple')
并查看它是否会更改路径的笔划。
祝你好运!
关于javascript - SVG 不会显示填充 d3.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557615/