【问题标题】:How to clone a group of elements in svg and show the clone in specified coordinate?如何克隆svg中的一组元素并在指定坐标中显示克隆?
【发布时间】:2021-02-12 18:41:20
【问题描述】:

SVG

<svg width="200" height="200">
    <g id="group">
        <rect x="10" y="10" width="50" height="20" fill="teal"></rect>
        <circle cx="35" cy="40" r="20" fill="red"></circle>
    </g>

    <circle id="ref_cycle" cx="135" cy="140" r="2" fill="green"></circle>

</svg>

我可以使用:

var copy = d3.select("#group").clone(true).attr("transform", "translate(20,00)"); 

拥有&lt;g id="group"&gt; 的副本并将其显示在页面中。

但我希望这个克隆组 red "circle" 中心与 SVG 中的 "ref_cycle" 中心对齐,但不会丢失组形状。我如何在代码中做到这一点?

非常感谢。

【问题讨论】:

  • 请阅读<use> svg 元素
  • 感谢您的信息@enxaneta,它很有用。我只是意识到我对翻译本身想得太多了。只需计算 ref_cycle center 和 circle center 之间的 x,y 偏移量并将该偏移量应用于新的 item.transform 可能会很好
  • 回答您自己的问题。它可能对其他人有用

标签: javascript svg d3.js


【解决方案1】:

这是我身边的一些 cmets 的工作代码,以防有人需要。

    var ref_cycle = d3.select("#ref_cycle"); 
        //^ get the reference cycle obj

    var clone_template = d3.select("#group"); 
        //^ get the template obj, for later select and clone use

    var clone_trans_x = ref_cycle.attr("cx") - clone_template.select("#inner-ref").attr("cx");
    var clone_trans_y = ref_cycle.attr("cy") - clone_template.select("#inner-ref").attr("cy");
        // to make select be simple, add an id tag in svg group's <circle id="inner-ref" ></circle> first.
        // do the math on offset of two objects    

    clone_template.clone(true).attr("transform", "translate(" + [clone_trans_x, clone_trans_y] + ")");
       // clone it 

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 2013-01-26
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多