下面贴上完整代码。要注意一点:创建svg节点时,要使用createElementNS函数并传入节点名称的命名空间。否则创建出来的节点默认为html dom而不是svg dom。这样的话,将其append到svg节点下时,不会显示。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<meta content="width=device-width;initial-scale=1">
<script>
function onLoad(){
var mysvg = document.getElementById("svg_my");
var rectObj = document.createElementNS("http://www.w3.org/2000/svg","rect");
if(rectObj){
rectObj.setAttribute("width",100);
rectObj.setAttribute("height",100);
rectObj.setAttribute("style","fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)");
mysvg.appendChild(rectObj);
alert("hello");
}
}
window.onload = onLoad;
</script>
</head>
<body>
<svg id="svg_my" style="border:1px solid #000;width:200px;height:200px" version="1.1" xmlns="http://www.w3.org/2000/svg">
</svg>
</body>
</html>
————————————————
原文链接:https://blog.youkuaiyun.com/tomatomas/article/details/50442497