svg - D3 : Append duplicates of a selection

标签 svg d3.js

我想创建一个 javascript 函数,它可以接受一个通用的 D3 选择,并将它的重复项附加到一个 SVG 对象。

这是一个最低限度的工作示例:

<!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 说这是不可能的here但那是很久以前的事了。

有没有人对如何实现这一目标有任何新想法?请记住,在函数内部 clone_selection我们不知道 x 中的 svg 元素是/是什么。

最佳答案

这是另一种可能性:长期做事。这解决了使用 <use> 的问题不能设置 style 的元素或 transform属性分开。

我很惊讶这个惊人的d3js库本身没有这样的功能,但这是我的黑客:

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;
}

关于svg - D3 : Append duplicates of a selection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517376/

相关文章:

javascript - 无论如何以编程方式将 D3 JS 图形导出到 LaTeX tikz 图形中?

d3.js - 你能在 d3 中通过 foo.style({color :blah, background :blah})?

javascript - 为 d3 项目加载 csv 文件时出现未定义的值

javascript - Webpack错误: Module has no exported member 'Rgb'

php - 在 SVG 中操作/翻译 <text>(添加边界框)

javascript - 如何在 d3.js 中绘制罗盘形状并为每个三 Angular 形着色不同?

angular - 无法绑定(bind)到 ':xlink:href',因为它不是 ':svg:image' 的已知属性

javascript - 从 html (webpack) 引用散列的 svg

javascript - 如何在raphael js中将一个元素放入另一个元素中?

javascript - d3.js zoom.translate 向量的单位是什么?