如何在svg中克隆一组元素并在指定的坐标中显示克隆



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)"); 

拥有CCD_ 1的副本并将其显示在页面中。

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

非常感谢。

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

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 

最新更新