一、什麼是 SVG ?
SVG,即可縮放矢量圖形(Scalable Vector Graphics)。
它是一種基於 XML 的標記語言,可以創建複雜的矢量圖形。
與位圖不同,矢量圖形可以無限縮放,而不會失去清晰度。這使得 SVG 成為一種非常方便的多媒體圖形格式,特別適合在網頁上使用。
下面是一個簡單的 SVG 示例:
<svg width="100" height="100"> <rect x="10" y="10" width="80" height="80" fill="red" /> </svg>
二、SVG 元素
SVG 通過在頁面上嵌入元素來創建圖形。以下是一些常用的 SVG 元素:
1. <rect> 元素
<rect> 元素創建一個矩形。可以設置它的位置、大小、顏色等屬性。
<svg width="100" height="100"> <rect x="10" y="10" width="80" height="80" fill="red" /> </svg>
2. <circle> 元素
<circle> 元素創建一個圓形。可以設置它的位置、半徑、顏色等屬性。
<svg width="100" height="100"> <circle cx="50" cy="50" r="40" fill="blue" /> </svg>
3. <line> 元素
<line> 元素創建一條直線。可以設置它的起點和終點的坐標、顏色等屬性。
<svg width="100" height="100"> <line x1="10" y1="10" x2="90" y2="90" stroke="black" /> </svg>
4. <text> 元素
<text> 元素在 SVG 中創建文本。
<svg width="100" height="100"> <text x="50" y="50" font-size="20" fill="black">Hello SVG!</text> </svg>
5. <path> 元素
<path> 元素在 SVG 中創建複雜的路徑。
<svg width="100" height="100"> <path d="M10 10 L50 90 L90 10" stroke="black" fill="none" /> </svg>
三、SVG 屬性
SVG 元素可以設置許多屬性,用於調整它們的外觀、位置和交互。以下是一些常用的 SVG 屬性:
1. width 和 height 屬性
width 和 height 屬性定義了 SVG 元素的寬度和高度。
<svg width="100" height="100"> ... </svg>
2. x 和 y 屬性
x 和 y 屬性定義 SVG 元素的左上角的坐標。
<svg> <rect x="10" y="10" ... /> <circle cx="50" cy="50" ... /> ... </svg>
3. fill 和 stroke 屬性
fill 和 stroke 屬性分別用於設置 SVG 元素的填充顏色和描邊顏色。
<rect fill="red" stroke="black" ... /> <circle fill="blue" stroke="black" ... /> <line stroke="black" ... /> <text fill="black" ... > ... </text> <path stroke="black" fill="none" ... />
4. transform 屬性
transform 屬性用於旋轉、縮放、平移和傾斜 SVG 元素。
<rect transform="rotate(45)" ... /> <circle transform="scale(2)" ... /> <line transform="translate(20,20)" ... /> <text transform="skewX(45)" ... >...</text> <path transform="scale(3) rotate(30)" ... />
四、SVG 交互
SVG 可以響應用戶交互,例如鼠標移動、點擊等。下面是一些常用的 SVG 交互事件:
1. onclick 事件
onclick 事件在用戶單擊 SVG 元素時觸發。下面的示例會在每次單擊時改變矩形的顏色。
<svg> <rect id="myRect" fill="red" width="100" height="100" onclick="document.getElementById('myRect').setAttribute('fill', 'blue');" /> </svg>
2. onmouseover 和 onmouseout 事件
onmouseover 和 onmouseout 事件在用戶將鼠標移到 SVG 元素上或移開時觸發。下面的示例會在鼠標移到圓形上時改變它的顏色。
<svg> <circle id="myCircle" fill="green" cx="50" cy="50" r="40" onmouseover="document.getElementById('myCircle').setAttribute('fill', 'blue');" onmouseout="document.getElementById('myCircle').setAttribute('fill', 'green');" /> </svg>
五、SVG 在 HTML 中的使用
在 HTML 中,可以通過下面的方式嵌入 SVG 圖像:
<svg width="100" height="100"> <rect x="10" y="10" width="80" height="80" fill="red" /> </svg>
SVG 也可以通過<img>標籤來嵌入:
<img src="myimage.svg" width="100" height="100" />
如果需要在 HTML 中直接嵌入 SVG 並與 HTML 元素進行交互,可以使用<object>或<iframe>元素:
<object type="image/svg+xml" data="myimage.svg" width="100" height="100"></object>
六、SVG MDN 參考文檔
以上內容僅是 SVG 的基本語法和常用元素,更多內容和詳細參數請參考 SVG MDN 文檔。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/187415.html