html页面中js动态新建svg元素

来源:互联网 发布:ubuntu安装mysql命令 编辑:程序博客网 时间:2024/04/30 03:34
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:lang="en">
<head>
<title>SVG test</title>
<script type="text/javascript"> 
function init() 

var svgLayer = document.getElementById('svgLayer'); 
var svgNS="http://www.w3.org/2000/svg";
var nodeRect = document.createElementNS(svgNS,"rect");
nodeRect.setAttribute("height",200);
nodeRect.setAttribute("width",200);
nodeRect.setAttribute("x",10);
nodeRect.setAttribute("y",10);
nodeRect.setAttribute("fill","#FFFFFF");
nodeRect.setAttribute("stroke","#000000");
    nodeRect.setAttribute("onclick","graphClick(evt)");

var animateGraph =  document.createElementNS(svgNS,"animate");
animateGraph.setAttribute("attributeType","XML");
animateGraph.setAttribute("attributeName","x");
animateGraph.setAttribute("from","50");
animateGraph.setAttribute("to","400");
animateGraph.setAttribute("dur","3s");
animateGraph.setAttribute("begin","3s");
    animateGraph.setAttribute("repeatCount","indefinite");

nodeRect.appendChild(animateGraph);

var svgContext =nodeRect.outerHTML;
svgLayer.innerHTML=svgContext;



function graphClick(evt)
{
var target = evt.target;
target.setAttribute("fill","#003C9D");
}
</script>
</head>

<body onload="init();">

<div id="svgDiv" align="center">

<svg id="svgLayer" width="400px" height="400px" viewBox="0 0 400 400" version="1.1" xmlns="http://www.w3.org/2000/svg">

</svg>
</div>
</body>
</html>
0 0