gpt4 book ai didi

javascript - HTML SVG 重用组 并为每个实例单独更改内部元素的属性

转载 作者:行者123 更新时间:2023-12-03 07:16:40 24 4
gpt4 key购买 nike

所以我想重用一个分组的 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>

最佳答案

肖恩说:

If the Web Components Custom Elements gets expanded to the SVG namespace,
more complex reuse will be possible

没错,您还不能制作自定义 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>`
}
});
svg{
width:100px;
height:100px;
background:grey;
fill:green;
}
<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>

SVG 的自定义元素是许多 oldskool SVG hacks 的现代解决方案

更新

如果 OP 想要一个带圆圈的 SVG,我们可以使用 shadowDOM 并且不显示 lightDOM 内的元素。我们甚至可以使用 undefined <rect> 元素(在 HTML 命名空间中),这样我们就可以轻松地将它们注入(inject) 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>

(my) 相关 StackOverflow 答案:Custom Elements and SVG

关于javascript - HTML SVG 重用组 <g> 和 <use> 并为每个实例单独更改内部元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63508259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com