【发布时间】:2016-03-21 06:21:18
【问题描述】:
目前,当我创建我的 SVG 文档时,我使用单个“画布”svg 对象,如下所示:
<svg id="svgCanvas" xmlns="http://www.w3.org/2000/svg"
xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"></svg>
然后我这样称呼它:
var svgCanvas = document.getElementById( "svgCanvas" );
然后将所有 SVG 对象作为子对象添加到该对象。例如,如果我创建一条线,我会这样做:
function createLine( id, x1, y1, x2, y2, color, width ){
var svgCanvas = document.getElementById( "svgCanvas" );
var line = document.createElementNS( svgNS, "line" );
line.setAttributeNS( null, "id", id );
line.setAttributeNS( null, "x1", x1 );
line.setAttributeNS( null, "y1", y1 );
line.setAttributeNS( null, "x2", x2 );
line.setAttributeNS( null, "y2", y2 );
line.setAttributeNS( null, "stroke", color );
line.setAttributeNS( null, "stroke-width", width );
svgCanvas.appendChild( line );
}
问题是我的图纸既有静态元素又有动态元素。有些东西会四处移动、被删除和重绘、改变形状等。其他东西是静态的并且永久保持不变。
当我清除我的画布时,我不想删除这些永久对象,我只想删除可变对象。所以,理想情况下,我希望有某种容器,它是 svg 对象(svgCanvas)的子对象,它只包含动态对象,这样当我清除时,我可以迭代该容器并删除它的子对象,然后离开静态对象,它们是主 svgCanvas 的子对象。
有没有办法制作这样一个“容器”,它是 svgCanvas 的子对象,并且仍然在 svg 上渲染容器中的所有对象?
另外,我可以通过移除容器来移除所有这些项目,而不需要遍历容器中的每个对象并单独移除它们吗?
* 更新 *
我添加了一个组如下:
function initialize(){
svgCanvas = document.getElementById( "svgCanvas" )
gDynamic = document.createElementNS( svgNS, "g" );
gDynamic.setAttribute( "id", "DynamicGroup" );
svgCanvas.appendChild( gDynamic );
}
但是,在这样做之后,添加到 svgCanvas 的任何对象都会出现,但子组中的任何对象都不会出现。
【问题讨论】:
标签: javascript svg containers element