以编程方式在SVG内添加SVG

问题描述 投票:1回答:1

我需要将SVG对象添加到附加到DOM的SVG对象内的特定位置。

但是无论何时,我在屏幕上都看不到任何渲染。我可以看到已添加SVG对象(在DevTools的Elements选项卡中),但未渲染它们。它们是纯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 );
});
javascript svg snap.svg
1个回答
0
投票

[这不起作用,因为您将圆附加到<svg>树之外,即直接在#root下,这可能是某种HTML元素,例如<div>

foreignObject问题基本上是相同的。不知道为什么要尝试将圆添加为foreignObject的子项(这将无法工作,因为您需要svg元素作为其父项)。我改用了html元素。

const s = Snap("#root");

var 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>';

var all = Snap.parse(svg);

// append the all.svg node. cool
s.append( all.node );

// get the red circle definition
var redc = all.select('#redc');

all.node.append(redc.node); // append as a child of the svg node

// foreign object
var foreign = document.createElementNS('http://www.w3.org/2000/svg',"foreignObject");
foreign.setAttribute('width', 500);
foreign.setAttribute('height', 150);
foreign.setAttribute('fill', 'pink');
var p = document.createElement('p');
foreign.appendChild(p);
var text = document.createTextNode("Hello World");
p.appendChild(text);

// add the foreign object to the correct part of the tree
all.node.append( foreign );
<script src="http://snapsvg.io/assets/js/snap.svg-min.js"></script>
<div id="root"></div>
© www.soinside.com 2019 - 2024. All rights reserved.