Hol*_*eid 2 html javascript code-reuse svg
所以我想重用分组的 svg 形状并为每个实例单独更改组内元素之一的一个属性。下面的简化示例创建了第二个圆圈,里面有一个矩形。我现在想使用 javascript 为每个形状单独更改“my-rect”矩形的“宽度”属性。使用 id "my-rect" 会改变两个矩形的宽度,但我只想改变一个。
我的目标(如果我的方法是无稽之谈):我必须绘制多个这些形状,唯一不同的是矩形的位置和宽度。
<svg height="1000" width="1000">
<a transform="translate(110,110)">
<g id="my-group">
<g>
<circle r="100" fill="#0000BF" stroke="black" stroke-width="2" fill-opacity="0.8"></circle>
</g>
<g>
<rect id="my-rect" y="-50" height="100" x="-50" width="50">
</rect>
</g>
</g>
</a>
<use xlink:href="#my-group" x="340" y="110"/>
</svg>Run Code Online (Sandbox Code Playgroud)
肖恩说:
如果 Web 组件自定义元素被扩展到 SVG 命名空间,
更复杂的重用将成为可能
这是真的,你不能制作自定义 SVG元素(还)。
但是您可以制作一个生成SVG的自定义元素:
customElements.define("rect-in-circle", class extends HTMLElement{
connectedCallback(){
const a = x => this.getAttribute(x);
this.innerHTML=`<svg viewBox="-100 -100 100 100">`+
`<g transform="translate(-50 -50)">`+
`<circle r="50" fill="#123456AB"/>`+
`<rect y="${a("y")}" height="${a("height")}"`+
`x="${a("x")}" width="${a("width" )}"/>`+
`</g></svg>`
}
});Run Code Online (Sandbox Code Playgroud)
svg{
width:100px;
height:100px;
background:grey;
fill:green;
}Run Code Online (Sandbox Code Playgroud)
<rect-in-circle x=-10 y=-10 width=20 height=20></rect-in-circle>
<rect-in-circle x=-40 y=-20 width=10 height=40></rect-in-circle>
<rect-in-circle x= 10 y= 20 width=30 height= 5></rect-in-circle>Run Code Online (Sandbox Code Playgroud)
SVG 的自定义元素是许多 oldskool SVG 黑客的现代解决方案
如果 OP 想要一个带圆圈的 SVG,我们可以使用 shadowDOM 以及不显示 lightDOM 中的元素这一事实。我们甚至可以使用未定义的 <rect>元素(在 HTML 命名空间中),这样我们就可以轻松地将它们注入到 SVG 字符串中。
<script>
customElements.define("rects-in-circles", class extends HTMLElement {
connectedCallback() {
setTimeout(() => {
const rects = [...this.children];
const width = rects.length * 100;
this.attachShadow({
mode: "open"
}).innerHTML = `<svg viewBox='0 0 ${width} 100'>` +
rects.map((rect, idx) => `<g transform='translate(${50+100*idx} 50)'>` +
`<circle r='50' fill='green'/>` +
rect.outerHTML +
`</g>`) + "</svg>";
})
}
});
</script>
<rects-in-circles>
<rect x=-10 y=-10 width=20 height=20></rect>
<rect x=-40 y=-20 width=10 height=40></rect>
<rect x=10 y=20 width=30 height=5></rect>
<rect x=-40 y=-40 width=50 height=50></rect>
</rects-in-circles>Run Code Online (Sandbox Code Playgroud)
(my)相关 StackOverflow 答案:自定义元素和 SVG
| 归档时间: |
|
| 查看次数: |
718 次 |
| 最近记录: |