我想从一个文件中加载一个 SVG,然后使用 svg.js 将它放在一个现有的 HTML SVG 元素(即一个组)中
我面临两个问题:
对不起,但我不知何故迷失了这项任务,希望有人好心帮助我。
不需要图书馆。
<div>
<svg viewBox="0 0 500 300">
<style>
svg { height: 180px;background:pink }
path { fill: green }
</style>
<heart width="250" x="0" y="0"/>
<australia x="250" y="0" width="250"/>
</svg>
<load-svg to="heart" src="//svg-cdn.github.io/heart.svg"></load-svg>
<load-svg to="australia" src="//svg-cdn.github.io/map-australia.svg"></load-svg>
</div>
<script>
customElements.define('load-svg', class extends HTMLElement {
async connectedCallback() {
this.attachShadow({mode:"open"})
.innerHTML = await (await fetch(this.getAttribute("src"))).text();
let svg = this.shadowRoot.querySelector("svg");
let to = this.getAttribute("to");
let container = this.parentNode.querySelector(to);
for(const attr of container.attributes) {
svg.setAttribute(attr.name,attr.value);
}
container.replaceWith(svg);
this.remove(); // Web Component did its job
}
});
</script>
australia - 心脏网络组件
原生 JavaScript Web 组件是最好的解决方案,因为您不必担心何时解析 HTML 或何时定义 Web 组件。
<load-svg>
标签将在定义Web组件时升级。<load-svg>
标签将执行唉原生 JavaScript Web Components 只能在 HTML NameSpace 中工作,
不在 SVG 命名空间中,所以
<svg>
<inject-svg src="...">
</svg>
不可能。
这意味着我们必须将
<load-svg>
Web 组件 放在 SVG 之外。
this.attachShadow({mode:"open"})
.innerHTML = await (await fetch(this.getAttribute("src"))).text();
加载外部 SVG 文件并将其注入 Web Component shadowDOM
let svg = this.shadowRoot.querySelector("svg");
let to = this.getAttribute("to");
let container = this.parentNode.querySelector(to);
在 shadowDOM 中加载对 SVG 的引用。
以及对
<heart>
或 <australia>
位置 inside 我们自己的 SVG 的引用。注意:这些是HTMLUnknownElement
,它们在 HTML 中不做任何事情(但表现得像一个 DIV),我们只是将它们用作临时容器。
for(const attr of container.attributes) {
svg.setAttribute(attr.name,attr.value);
}
将临时容器中的所有属性分配给 shadowDOM 中的 SVG
container.replaceWith(svg);
现在 shadowDOM 中的 SVG 已经完成,可以在我们的主 SVG 中占据一席之地
如果您注入具有不同
viewBox
设置x
和y
定位的SVG是一种痛苦,x="0" y="0"
不会在主SVG的左上角。提供的解决方案是针对一个相当简单的问题的非常复杂的方法。 只需使用 Ajax(jquery、axios、fetch)加载 svg,然后使用它:
// your group
const group = canvas.group()
// add svg
SVG(svg string).addTo(group)
你问题的评论也建议使用导入功能
group.svg(svg string)
那绝不会创建一个新的 svg,而是将其放入组中