SVG不会显示填充d3.js
问题描述:
我有一个SVG,我在Inkscape中做了,现在我想根据数据集值填充SVG中的颜色,但不知何故我不能设法显示一个简单的填充。不知道如何做到这一点。SVG不会显示填充d3.js
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
}
]
答
我误解你了,所以不理我刚才写的。进入()。追加( '路径')。
调用您选择的每种方法,并确保您的路径被选中,并且它们对应于正确的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('stroke', 'purple')
并查看它是否更改路径的笔划。
祝你好运!
.enter()。append('path')不起作用。控制台上没有错误。 – Imo
我错过了一件事。由于您正在追加路径元素,因此您需要设置“d”属性(selection.attr('d','路径字符串'))。你可以在这里阅读它https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths – sergeyz
什么是'路径字符串'在这里?我想改变d的值只是它的风格 – Imo