Gab*_*iel 5 javascript svg json d3.js
我正在从json文件中读取Arc信息并使用d3将它们可视化.实际上我d3.layout
用来分组数据.所以我必须读取这个文件在哪里tag
是我们的svg
标签是path
和路径value
的d
值,问题是d值将在读取和返回后更改 0
.我怎么看value
?我应该以不同方式组织我的json文件吗?这是我的代码:
json文件:
{"id": "svgContent","children": [
{"id": "circle1","tag": "path",
"value": "M0,160A160,160 0 1,1 0,-160A160,160 0 1,1 0,160M0,100A100,100 0 1,0 0,-100A100,100 0 1,0 0,100Z",
"children": [
{ "id": "point", "cx": "-67.59530401363443", "cy": "-93.03695435311894" },
{ "id": "point", "cx": "-109.37149937394265", "cy": "35.53695435311897" },
{ "id": "point", "cx": "1.4083438190194563e-14", "cy": "115" }
]
},
{"id": "circle2","tag": "path","value": "M0,260A260,260 0 1,1 0,-260A260,260 0 1,1 0,260M0,200A200,200 0 1,0 0,-200A200,200 0 1,0 0,200Z",
"children": [
{ "id": "point", "cx": "-126.37382924288177", "cy": "-173.93865379061367" },
{ "id": "point", "cx": "-204.477151003458", "cy": "66.43865379061373" },
{ "id": "point", "cx": "2.6329906181668095e-14", "cy": "215" }
]
}
]}
Run Code Online (Sandbox Code Playgroud)
这是我的源代码:
var w = 1200, h = 780;
var svgContainer = d3.select("#body").append("svg")
.attr("width", w).attr("height", h).attr("id", "svgContent");
var pack = d3.layout.partition();
d3.json("/data.json", function(error, root) {
if (error) return console.error(error);
var nodes = pack.nodes(root);
svgContainer.selectAll("pack").data(nodes).enter().append("svg")
.attr("id", function (d) { return d.id; }).append("path")
.attr("d", function (d) {
console.log(d.value);
return d.value; })
.attr("transform", "translate(600,0)");
});
Run Code Online (Sandbox Code Playgroud)
当我检查控制台时,我预期"M0,260A260,260 0 1,1 0,-260A260,260 0 1,1 0,260M0,200A200,200 0 1,0 0,-200A200,200 0 1,0 0,200Z"
但它会返回 0
,我该如何处理?
首先,我不太确定你d3.select("#body")
是否应该是d3.select("body")
?或者你有一个带有 id 的元素吗body
?
将 重置为 0 的问题value
是,使用d3.layout.partition()
值字段。您可以将值字段重命名为其他名称path
,然后将其设置为
.attr("d", function(d){
return d.path;
})
Run Code Online (Sandbox Code Playgroud)
您的代码的另一个问题是您添加了多个 svg 元素。如果您真的只想读取圆形路径并显示它们,那么以下代码可以完成这项工作:
var w = 1200,
h = 780;
var svgContainer = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("id", "svgContent");
d3.json("/data.json", function(error, root) {
if (error) return console.error(error);
svgContainer.selectAll("path")
.data(root.children)
.enter()
.append("path")
.attr("id", function (d) { return d.id; })
.attr("d", function(d) { return d.value})
.attr("transform", "translate(260,260)");
});
Run Code Online (Sandbox Code Playgroud)
无需分区布局。只需创建路径元素并添加 json 中的路径即可。如果你想显示圆圈,最好将它们放在 json 中的路径元素之外,因为你不能在路径元素内添加 svg 圆圈。
归档时间: |
|
查看次数: |
570 次 |
最近记录: |