簡體   English   中英

SVG 參考外部模式 ID

[英]SVG reference external pattern ID

我有兩個 SVG - 一個是矩形形狀的標志,另一個是背景圖案圖像的單個 svg。

徽標在文檔中多次重復,並且當<rect>設置為由#rect-fill ,具有#rect-fill元素 id 的模式 svg 的多個實例會破壞它並且背景圖像不顯示,所以現在我把它們分開了。

現在,由於模式 id 在#rect-container svg 之外,模式圖像不會顯示,也無法加載圖像。

無論如何,是否可以在另一個<svg>引用包含<svg>之外的rect的模式?

<!-- the logo svg -->
<svg id="rect-container" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- left squares -->
    <rect />
    <rect />
    <rect />

    <!-- right squares -->
    <rect />
    <rect />
    <rect />
</svg>

<!-- the background image pattern -->
<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
    <pattern id="rect-fill" patternUnits="userSpaceOnUse" x="0" y="0" width="1112" height="100%">
        <image xlink:href="../assets/images/hero.png"  width="100%" height="100%" preserveAspectRatio="xMinYMid slice"/>
    </pattern>
</svg>

<style>
/* Reference the pattern outside of the rect's svg */
#rect-container rect {
    fill(#rect-fill);
}
</style>

首先,您需要使用<defs>創建一個 svg 作為其他人可用的資源。

<!-- the background image pattern -->
<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
    <defs>
        <pattern id="rect-fill" patternUnits="userSpaceOnUse" x="0" y="0" width="1112" height="100%">
            <image xlink:href="../assets/images/hero.png"  width="100%" height="100%" preserveAspectRatio="xMinYMid slice"/>
        </pattern>
    </defs>
</svg>

然后您將能夠重用此元素。 更多信息在這里

<!-- the logo svg -->
<svg id="rect-container" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- left squares -->
    <rect fill="url(#rect-fill)"/>
</svg>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM