javascript - SVG 不会显示填充 d3.js

标签 javascript d3.js svg

我有一个在 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/

相关文章:

javascript - 使用包含 Django 的图像将 HTML 渲染为 PDF

javascript - 如何删除选定的元素 react

javascript - 100% 屏幕尺寸,无论分辨率如何

javascript - 如何在点击时更改图像的 ng-src

javascript - 从选择中获取 innerHTML

javascript - d3.js 多线图表中的系列标签

python - 将 json 数据从 django 发送到 d3.js

c# - 如何使用 svg .net 添加蒙版?

javascript - 基本垂直 SVG 线

php - 将分层 SVG 矢量图形转换为分层 EPS 矢量图形