这是我在 svg 中填充圆圈的代码。
var svgContainer = d3.select("body").append("svg")
.attr("width", 1000)
.attr("height", 1000);
var circles = svgContainer.selectAll("circle")
.data(nodes)
.enter()
.append("circle");
var circleAttributes = circles
.attr("cx", function (d) { return d.x_axis; })
.attr("cy", function (d) { return d.y_axis; })
.attr("r", function (d) { return d.radius; })
.attr('fill', 'green')
但是我不想在我的圈子内填充绿色,而是想在 url 在我的 json 数据中的每个圈子内填充不同的图像。我一直在尝试使用 .attr('fill', url(function(d) {return d.url})) 但它不起作用。我是 d3 的新手,谁能帮我解决这个问题?
最佳答案
从图像创建图案会占用过多内存,并且使用多个图像会造成严重的性能问题。因此,为了避免这种情况,我们可以在图像上使用剪辑路径。
像这样:
var config = {
"avatar_size": 100
}
var body = d3.select("body");
var svg = body.append("svg")
.attr("width", 500)
.attr("height", 500);
var defs = svg.append('svg:defs');
data = [{
posx: 100,
posy: 100,
img: "https://cdn4.iconfinder.com/data/icons/seo-and-data/500/pencil-gear-128.png",
}, {
posx: 200,
posy: 200,
img: "https://cdn4.iconfinder.com/data/icons/seo-and-data/500/gear-clock-128.png"
}, {
posx: 300,
posy: 300,
img: "https://cdn4.iconfinder.com/data/icons/seo-and-data/500/magnifier-data-128.png"
}];
svg .append('clipPath')
.attr('id','clipObj')
.append('circle')
.attr('cx',config.avatar_size/2)
.attr('cy',config.avatar_size/2)
.attr('r',config.avatar_size/2);
data.forEach(function(d,i){
svg.append('image')
.attr('xlink:href',d.img)
.attr('width',config.avatar_size)
.attr('height',config.avatar_size)
.attr('transform','translate('+parseInt(d.posx+config.avatar_size/2)+','+parseInt(d.posy+config.avatar_size/2)+')')
.attr('clip-path','url(#clipObj)');
});
我们也可以根据需要轻松地用新的裁剪区域替换裁剪区域。 这是代码笔的链接:http://codepen.io/anon/pen/VagxKp?editors=0010
关于javascript - 如何在 d3.js 中的 svg 圆圈内填充图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100296/