前往
大廳
主題

SVG 自學微筆記(05) - 在圖上加文字

冰抹茶拿鐵 | 2023-04-27 18:00:22 | 巴幣 0 | 人氣 130

不定更新、可能爛尾XD
學習資源: W3Schools、其他網路資料

之前有段時間挺忙的,所以停更了好一陣子 ಥ⌣ಥ,但至少還沒爛尾 ٩(๑❛ᴗ❛๑)۶。
原本按照W3Schools的SVG教學,這篇筆記應該是關於Path的內容,不過SVG的Path實在是有點複雜(也可以說是SVG中最難的部分),所以我會放在比較後面才去寫筆記整理重點。

SVG : 文字

  • 範例1

<svg height="300" width="400">
    <text x="0" y="30" fill="blue" fill-opacity="0.5"
    font-size="24px" font-weight="bolder">
    font-size="24px" font-weight="bolder">我愛SVG</text>
    <text x="0" y="70" fill="blue" fill-opacity="1"
    font-size="32px" font-weight="bolder">
    font-size="32px" font-weight="bolder">我愛SVG</text>
</svg>

  • 範例2
使用stroke相關屬性會蓋過fill屬性設定的文字顏色。
<svg height="300" width="400">
    <text x="0" y="30" fill="blue" fill-opacity="0.5" font-size="24px"
        stroke="green" stroke-width="0.5" font-weight="bolder">
我愛SVG</text>
    <text x="0" y="70" fill="blue" fill-opacity="1" font-size="32px"
        stroke="green" stroke-width="2" stroke-opacity="0.7" font-weight="bolder">
我愛SVG</text>
</svg>

  • 範例3
我們也可以使用transform屬性來旋轉(rotate)文字。
rotate(deg x,y)deg是旋轉角度,xy是旋轉起始點坐標。

<svg height="300" width="400">
    <text x="0" y="30" fill="blue" fill-opacity="0.5" font-size="24px"
        stroke="green" stroke-width="0.5" font-weight="bolder">
我愛SVG</text>
    <text x="15" y="75" fill="blue" fill-opacity="1" font-size="32px"
        font-weight="bolder" transform="rotate(30 20,40)">
我愛SVG</text>
</svg>

  • 範例4
<text></text>標籤裡面也可以有子標籤<tspan></tspan>
<svg height="300" width="400">
    <text x="15" y="50" fill="blue" font-size="32px" font-weight="bolder">我愛SVG
        <tspan x="15" y="90" font-size="24px">第一行文字</tspan>
        <tspan x="15" y="130" font-size="24px">第二行文字</tspan>
    </text>
</svg>

  • 範例5
<text></text>也可以被<a></a>包起來作為外部連結。
<svg height="300" width="400">
    <a href="https://www.w3schools.com/graphics/" target="_blank">
        <text x="15" y="50" fill="blue" font-size="32px" font-weight="bolder">我愛SVG</text>
    </a>
</svg>
(W3Schools教學寫的是xlink:href,不過我查過文件後,發現它被MDN Web Docs列為Deprecated,應該要用href取代。)

參考資料
SVG text - W3Schools
SVG Transformation - MDN
href and xlink:href on same element, and error handling

創作回應

更多創作