提问人:Rahul Raman 提问时间:3/15/2021 更新时间:9/24/2022 访问量:171
使用 JavaScript 动态添加组时如何更新 SVG
how to update a SVG when adding a group dynamically using javascript
问:
我正在制作一个电路构建器,我将使用 SVG 作为组件。我的 html 结构有一个空的 svg 标签,缩放到全宽和全高。我的 java 脚本在从工具栏拖动到画布(屏幕)时完成添加组件(svg 组)的工作。但由于某种原因,它没有显示在屏幕上。我应该更新我的 svg 或类似的东西来显示添加的元素吗?
function drop (e){
e.preventDefault();
const id = e.dataTransfer.getData("text");
const el = document.getElementById(id);
const dupEl = el.cloneNode(true);
dupEl.id = id+String(idCount);
idCount+=1;
document.getElementById("canvas").appendChild(dupEl);}
el 是 SVG 组元素 它看起来像
<g id ="gen">
<circle cx="90.327" cy="30.277" r="30" style="fill:none;stroke-width:2;stroke:#000"/>
<path d="m120.33 30.277h59.95" style="fill:none;stroke-width:2;stroke:#000"/>
<path d="m60.327 30.277h-60.05" style="fill:none;stroke-width:2;stroke:#000"/>
<text transform="matrix(1.7791 0 0 1.7791 -68.406 -26.148)" style="fill:#000000;font-family:sans-serif;font-size:10.583px;line-height:1.25;shape-inside:url(#rect1053);white-space:pre" xml:space="preserve"><tspan x="80.222656" y="39.933093"><tspan style="font-family:sans-serif;font-size:22.578px;font-variant-caps:normal;font-variant-east-asian:normal;font-variant-ligatures:normal;font-variant-numeric:normal;font-weight:bold">G</tspan></tspan></text>
</g>
带有 id canvas 的元素是
<svg class="canvasSvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="canvas">
</g>
</svg>
提前致谢。
答:
0赞
Rahul Raman
9/24/2022
#1
正如 @Robert Longson 在评论中提到的,div 不能显示 svg 组,父 svg 标签是必要的。
评论