<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
svg {
background:#eff3ef;
}
/* #r1 {*/
/* background: #faa; */
/* }*/
</style>
</head>
<body>
<h1>使用SVG绘制矩形</h1>
<svg width="500" height="400">
<rect id="r1" x="0" y="0" width="100" height="80" fill="rgba(255,0,0,0.2)" stroke="rgb(255,0,0)" stroke-width="6"></rect>
<rect id="r2" x="400" y="0" width="100" height="80" style="fill:rgba(0,255,0,0.2); stroke:rgb(0,255,0); stroke-width:6;"></rect>
<rect id="r3" x="0" y="320" width="100" height="80"></rect>
</svg>
<script>
//使用定时器让图形动起来
//var x = r3.x; //注意!SVG元素的属性不是传统的HTML DOM属性 SVGAnimatedLength{ }
var x = r3.getAttribute('x'); //读取属性
//console.log(typeof x); string
//console.log(x); 0
setInterval(function(){
x = parseInt(x) + 5;
r3.setAttribute('x', x); //修改属性
}, 42);
</script>
</body>
</html>
//动态添加方法
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
svg {
background:#eff3ef;
}
</style>
</head>
<body>
<h1>使用JS动态添加矩形</h1>
<svg id="svg8" width="500" height="400">
<rect x="0" y="320" width="100" height="80"></rect>
</svg>
<script>
//使用原生DOM操作添加新元素
//var r1 = document.createElement('rect'); 此方法创建的元素,默认命名空间 http://www.w3.org/2000/html
var r1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
r1.setAttribute('x', 0);
r1.setAttribute('y', 0);
r1.setAttribute('width', 100);
r1.setAttribute('height', 80);
svg8.appendChild( r1 );
</script>
</body>
</html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
svg {
background:#eff3ef;
}
/* #r1 {*/
/* background: #faa; */
/* }*/
</style>
</head>
<body>
<h1>使用SVG绘制矩形</h1>
<svg width="500" height="400">
<rect id="r1" x="0" y="0" width="100" height="80" fill="rgba(255,0,0,0.2)" stroke="rgb(255,0,0)" stroke-width="6"></rect>
<rect id="r2" x="400" y="0" width="100" height="80" style="fill:rgba(0,255,0,0.2); stroke:rgb(0,255,0); stroke-width:6;"></rect>
<rect id="r3" x="0" y="320" width="100" height="80"></rect>
</svg>
<script>
//使用定时器让图形动起来
//var x = r3.x; //注意!SVG元素的属性不是传统的HTML DOM属性 SVGAnimatedLength{ }
var x = r3.getAttribute('x'); //读取属性
//console.log(typeof x); string
//console.log(x); 0
setInterval(function(){
x = parseInt(x) + 5;
r3.setAttribute('x', x); //修改属性
}, 42);
</script>
</body>
</html>
//动态添加方法
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
svg {
background:#eff3ef;
}
</style>
</head>
<body>
<h1>使用JS动态添加矩形</h1>
<svg id="svg8" width="500" height="400">
<rect x="0" y="320" width="100" height="80"></rect>
</svg>
<script>
//使用原生DOM操作添加新元素
//var r1 = document.createElement('rect'); 此方法创建的元素,默认命名空间 http://www.w3.org/2000/html
var r1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
r1.setAttribute('x', 0);
r1.setAttribute('y', 0);
r1.setAttribute('width', 100);
r1.setAttribute('height', 80);
svg8.appendChild( r1 );
</script>
</body>
</html>