我正在使用 Cluster Dendogram . 我想根据我的聚类结果将图像插入到树状图的叶子中。 我该怎么做?
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<body>
<svg id="mySvg" width="80" height="80">
<defs id="mdef">
<pattern id="image" x="-100" y="-100" height="200" width="200" patternUnits="userSpaceOnUse" >
<image x="50" y="5" width="10" height="10" xlink:href="http://www.e-pint.com/epint.jpg"></image>
</pattern>
</defs>
</svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 2200;
var cluster = d3.layout.cluster()
.size([height, width - 160]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(40,0)");
d3.json("https://rawgit.com/bansaghi/d3.chart.layout.hierarchy/master/example/data/flare.json", function(error, root) {
var nodes = cluster.nodes(root),
links = cluster.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
//var circle = svg.append("circle")
// .style("fill", "red")
// .style("fill", "url(#image)");
node.append("circle")
.attr("r", 4.5);
//.style("fill", "black");e
node.append("image")
.attr("xlink:href", "http://www.e-pint.com/epint.jpg")
node.append("text")
.attr("dx", function(d) { return d.children ? -8 : 8; })
.attr("dy", 3)
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text(function(d) { return d.name; });
});
d3.select(self.frameElement).style("height", height + "px");
console.log(d3);
</script>
在这段代码中,我添加了样式部分和 node.append("image")
.attr("xlink:href", "http://www.e-pint.com/epint.jpg")
.
问题是我看不到充满图像的圆圈。有什么问题吗?
最佳答案
检查这个JSFiddle
这是向树叶添加图像的代码:
var leafnodes = svg.selectAll('g.leaf.node')
.append("image")
.attr("xlink:href", "http://www.e-pint.com/epint.jpg")
.attr("width", 10)
.attr("height", 10);
在此之前,叶节点被标记为 leaf
类,如下所示:
.attr("class", function(n) {
return n.children ? "inner node" : "leaf node";
})
更新:
要向节点添加不同的图像,您可以这样做:
var imgs = ['http://***.jpg',
'http://***.jpg',
'http://***.jpg'];
var leafnodes = svg.selectAll('g.leaf.node')
.append("image")
.attr("xlink:href", function (d) {
// get random image from array
return imgs[Math.floor(Math.random() * imgs.length)];
})
.attr("width", 10)
.attr("height", 10);
查看上面的 JSFiddle 以获取完整示例。
关于javascript - 使用 d3.js 将图像插入树状图的叶子中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824385/