如何在d3.js中的svg圈子中填充图像 [英] How to fill an image inside my svg circles in d3.js
问题描述
这是我的代码在我的svg中填充圆圈.
This is my piece of code filling circles in my 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的新手,有人可以帮助我解决此任务吗?
But instead of filling green color inside my circles, I want to fill different image inside each circles where the url is in my json data. I've been trying to use .attr('fill', url(function(d) {return d.url})) but it does not work. I am new to d3 and can anyone help me solving this task?
推荐答案
想象一下,您有一个像这样的数据集:
Imagine you have a dataset like this:
data = [{
posx: 100,
posy: 100,
img: "https://cdn0.iconfinder.com/data/icons/flat-round-system/512/android-128.png",
}, {
posx: 200,
posy: 200,
img: "https://cdn1.iconfinder.com/data/icons/social-media-set/24/Reverbnation-128.png"
}, {
posx: 300,
posy: 300,
img: "https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-128.png"
}]
在svg中使像这样的defs:
Make defs like this in svg like this:
var defs = svg.append('svg:defs');
遍历所有数据,并使用图像和圆进行尽可能多的定义.
在圆内填充像这样.style("fill", "url(#grump_avatar" + i + ")");
Iterate over all the data and make as many defs with image and circle.
Inside circles's fill pass the def's id like this .style("fill", "url(#grump_avatar" + i + ")");
data.forEach(function(d, i) {
defs.append("svg:pattern")
.attr("id", "grump_avatar" + i)
.attr("width", config.avatar_size)
.attr("height", config.avatar_size)
.attr("patternUnits", "userSpaceOnUse")
.append("svg:image")
.attr("xlink:href", d.img)
.attr("width", config.avatar_size)
.attr("height", config.avatar_size)
.attr("x", 0)
.attr("y", 0);
var circle = svg.append("circle")
.attr("transform", "translate(" + d.posx + "," + d.posy + ")")
.attr("cx", config.avatar_size / 2)
.attr("cy", config.avatar_size / 2)
.attr("r", config.avatar_size / 2)
.style("fill", "#fff")
.style("fill", "url(#grump_avatar" + i + ")");
})
工作代码此处
受此 SO答案
这篇关于如何在d3.js中的svg圈子中填充图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!