1. 程式人生 > >HTML5學習之路--SVG配合js製作動畫

HTML5學習之路--SVG配合js製作動畫

如果開發中需要用到與使用者互動的動畫。例如當用戶滑鼠移到頁面某個控制元件上,該控制元件會產生相應的變化。那麼此時可以使用svg標籤與js指令碼實現動畫的製作。

因為svg中包含的各個部分都可以獨立響應使用者的操作,所以可以直接在物件上加響應函式。如下面image中的onmouseover函式。

    <svg width="200px" height="200px">
	<image id="img_img" xlink:href="img/gps_off.png" x="50" y="50"
		height="100px" width="100px" onmouseover="onOverImg(event)"
		onmouseleave="onLeaveImg(event)" ></image>
    </svg>

然後我們只需要在js程式碼中定義響應函式,修改該物件的屬性即可:
var imgElement = document.getElementById("img_img");
imgElement.setAttribute("xlink:href", "img/gps_off.png");

以下是完整的html程式碼:
<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<meta charset="UTF-8">
		<title>Insert title here</title>
		<script type="text/javascript">
			function onOverImg(e) {
				var imgElement = document.getElementById("img_img");
				imgElement.setAttribute("xlink:href", "img/gps_on.png");
				imgElement.setAttribute("height", "140px");
				imgElement.setAttribute("width", "140px");
				imgElement.setAttribute("x", "30px");
				imgElement.setAttribute("y", "30px");
			}

			function onLeaveImg(e) {
				var imgElement = document.getElementById("img_img");
				imgElement.setAttribute("xlink:href", "img/gps_off.png");
				imgElement.setAttribute("height", "100px");
				imgElement.setAttribute("width", "100px");
				imgElement.setAttribute("x", "50px");
				imgElement.setAttribute("y", "50px");
			}
		</script>
	</head>
	<body>
		<svg width="200px" height="200px">
			<image id="img_img" xlink:href="img/gps_off.png" x="50" y="50"
			height="100px" width="100px" onmouseover="onOverImg(event)"
			onmouseleave="onLeaveImg(event)" ></image>
		</svg>
	</body>
</html>