腳本讓我們能完成各種複雜任務,也是實作動畫與互動最主流的方式。SVG 有兩套可用的 DOM 介面:因為它是 HTML 元素,所以普通的 DOM 操作完全適用;又因為它本質上是 XML 文件,因此另有一套專屬的 SVG DOM。以下分別來看。
先看一個用 JavaScript 動態建立 SVG 的例子:
<head>
<style>
#svgContainer {
width: 400px;
height: 400px;
background-color: #a0a0a0;
}
</style>
<script>
function CreateSVG() {
var XMLns = "https://www.w3.org/2000/svg";
var boxWidth = 300;
var boxHeight = 300;
var svgElem = document.createElementNS(XMLns, "svg");
svgElem.setAttributeNS(null, "viewBox", "0 0 " + boxWidth + " " + boxHeight);
svgElem.setAttributeNS(null, "width", boxWidth);
svgElem.setAttributeNS(null, "height", boxHeight);
svgElem.style.display = "block";
var g = document.createElementNS(XMLns, "g");
svgElem.appendChild(g);
g.setAttributeNS(null, 'transform', 'matrix(1,0,0,-1,0,300)');
// 線性漸層
var defs = document.createElementNS(XMLns, "defs");
var grad = document.createElementNS(XMLns, "linearGradient");
grad.setAttributeNS(null, "id", "gradient");
grad.setAttributeNS(null, "x1", "0%");
grad.setAttributeNS(null, "x2", "0%");
grad.setAttributeNS(null, "y1", "100%");
grad.setAttributeNS(null, "y2", "0%");
var stopTop = document.createElementNS(XMLns, "stop");
stopTop.setAttributeNS(null, "offset", "0%");
stopTop.setAttributeNS(null, "stop-color", "#ff0000");
grad.appendChild(stopTop);
var stopBottom = document.createElementNS(XMLns, "stop");
stopBottom.setAttributeNS(null, "offset", "100%");
stopBottom.setAttributeNS(null, "stop-color", "#0000ff");
grad.appendChild(stopBottom);
defs.appendChild(grad);
g.appendChild(defs);
// 邊框路徑
var coords = "M 0, 0";
coords += " l 0, 300";
coords += " l 300, 0";
coords += " l 0, -300";
coords += " l -300, 0";
var path = document.createElementNS(XMLns, "path");
path.setAttributeNS(null, 'stroke', "#000000");
path.setAttributeNS(null, 'stroke-width', 10);
path.setAttributeNS(null, 'stroke-linejoin', "round");
path.setAttributeNS(null, 'd', coords);
path.setAttributeNS(null, 'fill', "url(#gradient)");
path.setAttributeNS(null, 'opacity', 1.0);
g.appendChild(path);
var svgContainer = document.getElementById("svgContainer");
svgContainer.appendChild(svgElem);
}
</script>
</head>
<body onload="CreateSVG()">
<div id="svgContainer"></div>
</body>
注意到沒有?寫法與操作普通 HTML 元素幾乎一模一樣:
選擇元素:document.getElementById
建立元素:document.createElementNS
建立子元素的另一種方式:element.createChildNS
加入元素:node.appendChild
設定屬性:element.setAttributeNS / element.setAttribute
其他常見操作還包括:
取得屬性值:element.getAttributeNS / getAttribute
檢查屬性是否存在:element.hasAttributeNS
移除屬性:element.removeAttributeNS
父元素、子元素與兄弟節點:element.parentNode / firstChild / nextSibling
DOM 樹的節點結構、物件之間的繼承關係也都大同小異,這裡不再細說,需要的話請參考後面的 DOM Core 文件。
有一點務必注意:由於 SVG 本質是 XML 文件,所用的 DOM 方法幾乎都帶 NS 字尾,用來指定 namespace。若建立元素時已提供 namespace,而且不存在多重 namespace 的問題,設定屬性時用不帶 NS 的版本也可以;但強烈建議一律使用帶 NS 的版本,因為它在任何情況下都能正常運作,包括多 namespace 並存的複雜結構。
關於 SVG DOM 與標準 DOM 的完整差異,我沒有找到太全面的資料,目前確定的是屬性賦值方式不同。上面我們用 setAttributeNS 設定屬性,而在 SVG DOM 中,可以用更物件導向的方式透過點號直接赋值。兩種寫法對比如下。
普通 DOM 方式:
element.setAttribute("x", "10");
element.setAttribute("y", "20");
element.setAttribute("width", "100%");
element.setAttribute("height", "2em");
SVG DOM 方式:
element.x.baseVal.value = 10; element.y.baseVal.value = 20; element.width.baseVal.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PERCENTAGE, 100); element.height.baseVal.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_EMS, 10);
差別的意義在於:DOM 腳本屬於傳統風格,特色是必須組出「值字串」再設定;而 SVG DOM 不需要組字串,因此效能優於 DOM 腳本。在做大量屬性更新或高頻動畫時,這個差異會被放大。
若要把腳本放進 SVG 裡,需要使用 script 元素(並以 CDATA 包裹內容),除此之外與放在外部 HTML 中並無不同。看例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head></head>
<body>
<svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink"
width="300" height="300">
<script type="text/ecmascript">
<![CDATA[
function showRectColor() {
alert(document.getElementById("myBlueRect").getAttributeNS(null, "fill"));
}
function showRectArea(evt) {
var width = parseFloat(evt.target.getAttributeNS(null, "width"));
var height = parseFloat(evt.target.getAttributeNS(null, "height"));
alert("The rectangle area is: " + (width * height));
}
function showRootChildrenNr() {
alert("Nr of Children: " + document.documentElement.childNodes.length);
}
]]>
</script>
<g id="firstGroup">
<rect id="myBlueRect" width="100" height="50" x="40" y="20" fill="blue"
onclick="showRectArea(evt)" />
<text x="40" y="100" onclick="showRectColor()">
Click on this text to show rectangle color.
</text>
<text x="40" y="130">Click on rectangle to show rectangle area.</text>
<text x="40" y="160" onclick="showRootChildrenNr()">
Click on this text to show the number of child
<tspan x="40" dy="20">elements of the root element.</tspan>
</text>
</g>
</svg>
</body>
</html>
這個例子示範了三種取得 DOM 物件的常見途徑:
1. 透過 document.getElementById、getElementsByClassName 之類的方法取得。
2. 透過 document.documentElement 或 document.rootElement 取得根物件。
3. 透過事件參數 evt.target 取得觸發事件的物件——這種方式不必事先設定 id 就能拿到來源元素,寫事件委派時特別好用。
其餘腳本邏輯與一般 DOM 完全一致。
腳本索引:https://msdn.microsoft.com/zh-cn/library/ff971910(v=vs.85).aspx
MDN 開發中心:https://developer.mozilla.org/en/SVG
官方規範:https://www.w3.org/TR/SVG11/
DOM Core Object API:https://reference.sitepoint.com/javascript/Document