D3:附加选择的重复 [英] D3: Append duplicates of a selection
问题描述
我想创建一个javascript函数,它可以采用通用的D3选择,并将它的副本附加到SVG对象。
I'd like to create a javascript function which can take a generic D3 selection, and append duplicates of it to an SVG object.
这里是一个最低工作示例:
Here's a minimum working example:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
svg = d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300);
circle = svg.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 20)
function clone_selection(x, i) {
for (j = 0; j < i; j++) {
// Pseudo code:
// svg.append(an exact copy of x, with all the attributes)
}
}
clone_selection(circle, 5);
</script>
Mike Bostock说这是不可能的在这里,但是那是一段时间。
Mike Bostock said that this was impossible here but that was a while back.
有人有任何新的想法如何实现这一点?记住,在函数 clone_selection
中我们不知道x中有什么svg元素。
Does anyone have any new thoughts about how this might be achieved? Remember, inside the function clone_selection
we have no idea what svg element(s) is/are in x.
推荐答案
这里有另一种可能性:做很多事情。这使用< use>
元素来处理问题,其中不能设置 style
或 transform
属性。
Here's another possibility: do things the long way. This gets round the problem with using <use>
elements where you can't set the style
or transform
attributes separately.
我惊讶于 d3js
这不是本机的,但这里是我的黑客:
I'm surprised the amazing d3js
library doesn't feature something like this natively, but here's my hack:
function clone_d3_selection(selection, i) {
// Assume the selection contains only one object, or just work
// on the first object. 'i' is an index to add to the id of the
// newly cloned DOM element.
var attr = selection.node().attributes;
var length = attr.length;
var node_name = selection.property("nodeName");
var parent = d3.select(selection.node().parentNode);
var cloned = parent.append(node_name)
.attr("id", selection.attr("id") + i);
for (var j = 0; j < length; j++) { // Iterate on attributes and skip on "id"
if (attr[j].nodeName == "id") continue;
cloned.attr(attr[j].name,attr[j].value);
}
return cloned;
}
这篇关于D3:附加选择的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!