gpt4 book ai didi

javascript - 将 SVG 嵌入另一个 SVG、jQuery

转载 作者:行者123 更新时间:2023-12-01 02:08:52 25 4
gpt4 key购买 nike

我将许多空白 SVG(例如马赛克)附加到名为“背景”的 svg,如下所示:

var baseView = document.createElementNS(svgNS,"rect"); 
baseView.setAttributeNS(null,"id",id);
baseView.setAttributeNS(null,"x",xOff);
baseView.setAttributeNS(null,"y",yOff);
baseView.setAttributeNS(null, 'height', bD);
baseView.setAttributeNS(null, 'width', bD);
baseView.setAttributeNS(null,"fill",'red');
baseView.setAttributeNS(null,"stroke","none");
document.getElementById("background").appendChild(baseView);

背景定义位置:

<svg id="background" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

然后我尝试在 baseView SVG 中嵌入另一个 SVG:

var trunkView = document.createElementNS(svgNS, 'rect'); 
trunkView.setAttributeNS(null,"id",trunkID);
trunkView.setAttributeNS(null,"x",xInset);
trunkView.setAttributeNS(null,"y",yInset);
trunkView.setAttributeNS(null, 'height', (bD/2 + branchWidth));
trunkView.setAttributeNS(null, 'width', trunkWidth);
trunkView.setAttributeNS(null,"fill","black");
trunkView.setAttributeNS(null,"stroke","none");
baseView.appendChild(trunkView);

我也尝试过:

document.getElementById(id).appendChild(branchView);

当我直接附加到“background”svg时,子“trunkView”会正确附加并且可见,但当它嵌入“baseView”中时则不会。根据浏览器,它说它在那里但没有显示。有什么想法吗?

最佳答案

如果您查看“rect”元素的规范,您会看到以下内容:

Content model:
Any number of the following elements, in any order:
animation elements — ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’
descriptive elements — ‘desc’, ‘metadata’, ‘title’

因此,“rect”元素不允许作为“rect”元素的内容,这可以解释为什么它不渲染。

参见:https://www.w3.org/TR/SVG11/shapes.html#RectElement

编辑:

要对元素进行分组,您可以使用“g”元素。像这样:

var baseView = document.createElementNS('http://www.w3.org/2000/svg',"rect"); 
baseView.setAttributeNS(null,"id",5);
baseView.setAttributeNS(null,"x",5);
baseView.setAttributeNS(null,"y",5);
baseView.setAttributeNS(null, 'height', 100);
baseView.setAttributeNS(null, 'width', 100);
baseView.setAttributeNS(null,"fill",'red');
baseView.setAttributeNS(null,"stroke","none");
document.getElementById("group").appendChild(baseView);
var trunkView = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
trunkView.setAttributeNS(null,"id",10);
trunkView.setAttributeNS(null,"x",40);
trunkView.setAttributeNS(null,"y",40);
trunkView.setAttributeNS(null, 'height', 100);
trunkView.setAttributeNS(null, 'width', 100);
trunkView.setAttributeNS(null,"fill","black");
trunkView.setAttributeNS(null,"stroke","none");
document.getElementById("group").appendChild(trunkView);
<svg id="background" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="group"></g>
</svg>

参见:https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g

关于javascript - 将 SVG 嵌入另一个 SVG、jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com