我在一個苗條的應用程式中渲染了一些動態生成的 SVG,這些 SVG 生成為字串,然后放入單獨的<svg>標簽中:
<script lang="ts">
import { IconGenerator } from "../icons/iconGenerator";
let icons = [];
for (let index = 0; index < 15; index ) {
icons.push(IconGenerator.generate());
}
</script>
<div>
{#each icons as icon}
<div>
<svg viewBox="0 0 600 600" width="300" height="300">
{@html icon}
</svg>
</div>
{/each}
</div>
到目前為止,這很好用,但我想開始使用每個圖示不同的漸變。
如何定義漸變的 id 并將它們的范圍僅限于它們所屬的圖示,而不是將它們應用于整個頁面?
我研究了一些處理制作唯一 id 的 SVG 注入器庫,但它們似乎都是為非動態 svg 制作的,該 url 不是從字串動態創建的。
uj5u.com熱心網友回復:
通過use:action使用 Shadow DOM 的版本,其中 id 不會干擾REPL
<script>
let icons = [
`<defs><linearGradient id="gradient" gradientTransform="rotate(90)">
<stop offset="5%" stop-color="gold" />
<stop offset="95%" stop-color="red" />
</linearGradient></defs>
<circle cx="100" cy="100" r="100" fill="url(#gradient)"/>`,
`<defs><linearGradient id="gradient" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="teal"/>
<stop offset="50%" stop-color="darkblue" stop-opacity="50"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient></defs>
<rect id="rect" width="200" height="200" rx="15" fill="url(#gradient)"/>`
]
function shadow(node) {
const shadowRoot = node.attachShadow({mode: 'open'})
const children = Array.from(node.children)
children.forEach(child => shadowRoot.appendChild(child))
}
</script>
<div>
{#each icons as icon, index}
<div class="shadow-host" use:shadow>
<svg viewBox="-50 -50 300 300" width="200" height="200" style="display:block;">
{@html icon}
</svg>
</div>
{/each}
</div>
<style>
.shadow-host {
border: 2px solid lightgrey;
}
</style>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/492517.html
