嗨,我正在尝试将方形图像添加到圆形 Node ,但将图像裁剪为 Node 大小。我已成功添加图像,但似乎无法将它们裁剪到圆形 Node 。对我做错了什么有什么建议吗?
var node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag)
.on('mouseover', connectedNodes)
.on('mouseout', allNodes)
.on('contextmenu', function(d){d3.event.preventDefault();tip.show(d);}) //.on('mousedown', tip.show)
.on('mouseleave', tip.hide);
node.append("circle")
.attr("r", function(d) { return d.degree;})
.style("fill", function (d) {return color(d.group);})
node.append("image")
.attr("xlink:href", function(d) { return d.image;})
.attr("x", function(d) { return -25;})
.attr("y", function(d) { return -25;})
.attr("height", 50)
.attr("width", 50);
如果没有任何图像,我还想在那里显示 Node 。
最佳答案
使用 svg 剪辑路径。
代码示例:
var nodes = [{
"id": "0",
"name": "ETCO I",
"degree": 50,
x: 100,
y: 150
}, {
"id": "1",
"name": "PINKERTON Eidel ",
"degree": 25,
x: 200,
y: 100
}];
var container = d3.select("svg");
var node = container.append("g").selectAll(".node")
.data(nodes)
.enter()
.append("g")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
node.append("clipPath")
.attr("id",function(d,i){ return "node_clip"+i })
.append("circle")
.attr("r",function(d) {
return d.degree-2; //-2 to see a small border line
});
node.append("circle")
.attr("r", function(d) {
return d.degree;
})
.style("fill", "blue");
node.append("image")
.attr("xlink:href", function(d) {
return "https://image.freepik.com/free-icon/group-of-people-in-a-formation_318-44341.png";
})
.attr("x",function(d){ return -d.degree })
.attr("y",function(d){ return -d.degree })
.attr("height", function(d){ return d.degree*2 })
.attr("width", function(d){ return d.degree*2 })
.attr("clip-path",function(d,i){ return "url(#node_clip"+i+")" });
svg {
background: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width=500 height=200></svg>
关于javascript - 需要将方形图像附加到圆形 Node d3.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153529/