SVG 指令碼
SVG + JavaScript
SVG 可以與 JavaScript 一起使用來修改和動畫化 SVG 元素。
SVG 簡單指令碼
在此示例中,我們建立了一個半徑為 25 的紅色圓。單擊按鈕將半徑更改為 50
這是 SVG 程式碼
示例
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle1" cx="50" cy="50" r="25" style="fill:red;" />
</svg>
<input type="button" value="更改半徑" onclick="changeRadius()" />
<script>
function changeRadius() {
document.getElementById("circle1").setAttribute("r", "50");
}
</script>
自己動手試一試 »
程式碼解釋
- 在
<circle>
元素中新增一個id
屬性 - 在
<script>
標籤內建立一個指令碼 - 使用
getElementById()
函式獲取對 SVG 元素的引用 - 使用
setAttribute()
函式更改r
屬性 - 新增一個
<input type="button">
元素,以便在單擊時執行 JavaScript
SVG 更改 CSS
在此示例中,我們建立了一個紅色圓。單擊按鈕將填充顏色更改為綠色
這是 SVG 程式碼
示例
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle2" cx="50" cy="50" r="25" style="fill:red;" />
對不起,您的瀏覽器不支援內嵌 SVG。
</svg>
<input type="button" value="更改樣式" onclick="changeStyle()" />
<script>
function changeStyle() {
document.getElementById("circle2").style.fill="green";
}
</script>
自己動手試一試 »
程式碼解釋
- 在
<circle>
元素中新增一個id
屬性 - 在
<script>
標籤內建立一個指令碼 - 使用
getElementById()
函式獲取對 SVG 元素的引用 - 使用
style.fill
設定新的填充顏色 - 新增一個
<input type="button">
元素,以便在單擊時執行 JavaScript
SVG 更改屬性值和 CSS
在此示例中,我們建立了一個紅色圓。單擊按鈕可更改半徑、x 位置、填充顏色,並新增描邊顏色
這是 SVG 程式碼
示例
<svg width="200" height="120" xmlns="http://www.w3.org/2000/svg">
<circle id="circle3" cx="50" cy="60" r="25" style="fill:red;" />
</svg>
<input type="button" value="更改圓" onclick="changeMe()" />
<script>
function changeMe() {
var c = document.getElementById("circle3");
c.setAttribute("r", "50");
c.setAttribute("cx", "150");
c.style.fill="green";
c.style.stroke="red";
}
</script>
自己動手試一試 »
SVG 動畫指令碼
在此示例中,我們建立了一個紅色圓。單擊兩個按鈕可啟動和停止動畫
這是 SVG 程式碼
示例
<svg width="600" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle4" cx="50" cy="50" r="50" style="fill:red;" />
</svg>
<script>
var t = null;
function start() {
if(t == null) {
t = setInterval(animate, 20);
}
}
function stop() {
if(t != null) {
clearInterval(t);
t = null;
}
}
function animate() {
var circle = document.getElementById("circle4");
var cx = circle.getAttribute("cx");
var newCX = 2 + parseInt(cx);
if(newCX > 600) {
newCX = 50;
}
circle.setAttribute("cx", newCX);
}
</script>
<br/>
<input type="button" value="Start" onclick="start()" />
<input type="button" value="Stop" onclick="stop()" />
自己動手試一試 »
程式碼解釋
start()
和stop()
函式啟動和停止動畫- 動畫透過設定一個定時器 (t) 開始,該定時器使用
setInterval()
函式每 20 毫秒呼叫一次animate()
函式 - 透過清除 t 定時器來停止動畫
- 動畫在
animate()
函式內部執行 - 使用
getElementById()
函式獲取對<circle>
元素的引用 - 使用
getAttribute()
函式獲取cx
屬性的值 - 使用
parseInt()
將cx
屬性的值轉換為數字。然後將 2 加到cx
值上 - 測試
newCX
值是否大於 600(這是 SVG “視窗”的寬度),然後將其重置為 50(這是原始的起始位置) - 使用
setAttribute()
函式將newCX
值放入<circle>
元素的cx
屬性中。這將圓移動到新的 cx 位置