【问题标题】:add SVGs inside an SVG programmatically以编程方式在 SVG 中添加 SVG
【发布时间】: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


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2016-10-20
    • 2013-05-29
    • 2019-06-26
    • 1970-01-01
    • 2018-01-21
    • 2012-09-23
    • 1970-01-01
    相关资源
    最近更新 更多