SVG 脚本
简单脚本示例
html
<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="Change Radius" onclick="changeRadius()" />
<script>
function changeRadius() {
document.getElementById("circle1").setAttribute("r", "50");
}
</script>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
修改 CSS
html
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle2" cx="50" cy="50" r="25" style="fill:red;" />
Sorry, your browser does not support inline SVG.
</svg>
<input type="button" value="Change Style" onclick="changeStyle()" />
<script>
function changeStyle() {
document.getElementById("circle2").style.fill="green";
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
修改属性和css
html
<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="Change Circle" 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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
通过脚本实现动画
html
<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()" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34