我正在尝试将图像附加到矩形上,并且图像位置存在于名为 arrFileUrl 的数组中。这种颜色的节点是白色的,我想将这些图像附加到每个生成的矩形上。我怎样才能做到这一点?
var arrFileUrl = [], arrBrightness = [], arrPattern = [], arrSize = [];
var width = 1260,
height = 1200;
var fill = d3.scale.category10();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.csv("data/Images.csv", function(error, data) {
data.forEach(function(d) {
arrFileUrl.push(d['FingerImageName']);
});
var nodes = d3.range(arrSize.length).map(function(i) {
return {index: i};
});
var force = d3.layout.force()
.nodes(nodes)
.gravity(0.05)
.charge(-1700)
.friction(0.5)
.size([width, height])
.on("tick", tick)
.start();
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("rect")
.attr("class", "node")
.attr("width", 120)
.attr("height", 160)
.style("fill", "#fff")
.style("stroke", "black")
.call(force.drag);
node.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", 16)
.attr("y", 16)
.attr("width", 100)
.attr("height", 120);
svg.style("opacity", 1e-6)
.transition()
.duration(1000)
.style("opacity", 1);
function tick(e) {
// Push different nodes in different directions for clustering.
var k = 6 * e.alpha;
nodes.forEach(function(o, i) {
o.y += i & 1 ? k : -k;
o.x += i & 2 ? k : -k;
});
node.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; });
}
});
最佳答案
这样做:
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g");//make groups
//add rectangle to the group
node.append("rect")
.attr("class", "node")
.attr("width", 120)
.attr("height", 160)
.style("fill", "#fff")
.style("stroke", "black")
.call(force.drag);
//add image to the group
node.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", 16)
.attr("y", 16)
.attr("width", 100)
.attr("height", 120);
勾选功能翻译整个组
function tick(e) {
// Push different nodes in different directions for clustering.
var k = 6 * e.alpha;
nodes.forEach(function(o, i) {
o.y += i & 1 ? k : -k;
o.x += i & 2 ? k : -k;
});
//do transform
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
}
代码中的问题:
- 您将
图像
附加到矩形
DOM中,这就是图像不可见的原因。 - 在
tick 函数
中,您单独移动 x 和 y,而不是图像的 x 和 y,该方法应该将它们成组移动并按上面的方法平移该组。
关于javascript - 无法在 d3.js 中的节点上附加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901961/