【发布时间】:2018-07-09 15:27:53
【问题描述】:
我需要将 SVG 对象添加到附加到 DOM 的 SVG 对象内的特定位置。
但每当我这样做时,我都看不到屏幕上呈现任何内容。我可以看到添加了 SVG 对象(在 DevTools 的元素选项卡中),但它们没有被渲染。它们是纯 SVG(没有包裹在像 DIV 这样的 HTML 元素上)。
我尝试使用 ajax 加载 SVG 并添加它们,尝试使用 Snap,尝试将这些元素放在 <defs> 标记中,使用 Snap 找到它们,然后将它们添加到主 Snap 对象。似乎没有任何效果。对象总是被添加但不被渲染。
这可能吗?
SVG
<svg width="400" height="300" style="background: gray">
<defs>
<circle id="redc" cx="50" cy="50" r="50" style="fill: red" />
<circle id="yelc" cx="40" cy="40" r="40" style="fill: yellow" />
</defs>
<circle id="bluc" cx="200" cy="200" r="50" style="fill: blue" />
</svg>
JavaScript
const s = Snap("#root");
Snap.load('images/all.svg', function(data){
var all = data;
// append the all.svg node. cool
s.append( all.node );
// get the red circle definition
var redc = all.select('#redc');
s.append(redc.node); // doesn't work
});
有异物:
Snap.load('images/all.svg', function(data){
var all = data;
// append the all.svg node. cool
s.append( all.node );
// get the red circle definition
var redc = all.select('#redc');
// foreign object
var foreign = document.createElementNS('http://www.w3.org/2000/svg',"foreignObject");
foreign.setAttribute('width', 500);
foreign.setAttribute('height', 150);
foreign.appendChild(redc);
// add the foreign object - doesn't work
s.append( foreign );
});
【问题讨论】:
-
当然可以,但如果没有看到您的代码,我们无法告诉您您做错了什么。
-
@RobertLongson 刚刚添加了一些代码,谢谢大佬
标签: javascript svg snap.svg