首页 > 解决方案 > HTML 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>

标签: javascripthtmlsvgcode-reuse

解决方案


肖恩 说:

如果 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>`
  }
});
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 hack 的现代解决方案

更新

如果 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>

(my)相关 StackOverflow 答案:自定义元素和 SVG


推荐阅读