SVG 掩码的范围



我正在使用Javascript在自定义轮播中动态插入基于SVG的控件/计时器。作为参考,这是 SVG(如果您喜欢它,请随意使用它,顺便说一句)......

<svg class="timer-control" width="48" height="48" viewbox="0 0 48 48" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<mask id="timer-animask">
<circle cx="50%" cy="50%" r="24" fill="#fff" />
<circle cx="50%" cy="50%" r="20" fill="#000" />
</mask>
</defs>
<g mask="url(#timer-animask)">
<path id="timer-ring" transform="translate(24,24)"/>
</g>
<g id="pause">
<rect x="18" y="16" width="4" height="16"></rect>
<rect x="25" y="16" width="4" height="16"></rect>
</g>
<g id="play">
<polygon points="0,0 0,18 18,9" transform="translate(18,15)"/>
</g>
</svg>

我可以使用两种方法来渲染它...我可以将 SVG 直接插入 DOM 中,也可以插入带有外部 SVG 文件链接的object

这是问题所在...理想情况下,我只想将 SVG 直接插入到 DOM 中(再次,在这里使用 Javascript),但是当我有多个 SVG 实例时,掩码会中断,因为它引用了一个重复的 id,因为 SVG 绑定到 DOM。

我可以想到两种解决方法,这两种解决方法都不喜欢:

选项 1:对象 SVG

改为嵌入object。这会将 SVG 范围保留在对象/文件的本地,因此掩码不会中断 [由于 id 冲突]。但是,这意味着我必须在 Javascript 中处理动态文件路径,并且我不能再使用 CSS 来设置 SVG 组件的样式(我必须专门使用 Javascript 来访问内部并操作属性)。这似乎笨重、效率低下且不优雅。它会起作用,但我不是粉丝。

选项 2:带动态 ID 的 DOM 插入

在我将 SVG 直接插入 DOM 之前生成一个随机 id 种子,并将该种子附加到所有 SVG 的组 ID 中。

例如

<svg class="timer-control" id="timer-control-345235" width="48" height="48" viewbox="0 0 48 48" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<mask id="timer-animask-345235">
<circle cx="50%" cy="50%" r="24" fill="#fff" />
<circle cx="50%" cy="50%" r="20" fill="#000" />
</mask>
</defs>
<g mask="url(#timer-animask-345235)">
<path id="timer-ring-345235" transform="translate(24,24)"/>
</g>
<g id="pause-345235">
<rect x="18" y="16" width="4" height="16"></rect>
<rect x="25" y="16" width="4" height="16"></rect>
</g>
<g id="play-345235">
<polygon points="0,0 0,18 18,9" transform="translate(18,15)"/>
</g>
</svg>

与选项 1 一样,这是功能性的,它允许我使用 CSS 来操作 SVG(这很好),但它似乎也很笨拙和不优雅。

问题

所以这是我的问题...是否有我还没有考虑过的更好的方法,或者选项 1 或 2真的是我的最佳选择?

或者您可以在顶部包含一次 SVG。 然后通过<use>引用所需的控件。

#pause-345235
{
fill: orange;
}
#play-345235
{
fill: green;
}
<svg class="timer-control" id="timer-control-345235" width="0" height="0" viewbox="0 0 48 48" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<mask id="timer-animask-345235">
<circle cx="50%" cy="50%" r="24" fill="#fff" />
<circle cx="50%" cy="50%" r="20" fill="#000" />
</mask>
</defs>
<g mask="url(#timer-animask-345235)">
<path id="timer-ring-345235" transform="translate(24,24)"/>
</g>
<g id="pause-345235">
<rect x="18" y="16" width="4" height="16"></rect>
<rect x="25" y="16" width="4" height="16"></rect>
</g>
<g id="play-345235">
<polygon points="0,0 0,18 18,9" transform="translate(18,15)"/>
</g>
</svg>

<svg width="48" height="48">
<use xlink:href="#pause-345235"/>
</svg>
<svg width="48" height="48">
<use xlink:href="#play-345235"/>
</svg>

最新更新