我读过几个类似的问题,但我的代码无法正常工作。 我想在用户单击SVG区域时添加一个SVG元素。
这是我的HTML5与SVG,它可以正确渲染:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="svgdraw.js"></script>
</head>
<body>
<svg id="canvas" width="500" height="500">
<circle cx="80" cy="80" r="50" fill="blue"/>
</svg>
</body>
</html>
这是在单击事件上执行的JavaScript代码:
var svgDocument = document.getElementById('canvas');
var svgns = "http://www.w3.org/2000/svg";
var shape = svgDocument.createElementNS(svgns,"circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
document.getElementById('canvas').appendChild(shape);
在 Google Chrome 中,我收到一个错误消息,说 createElementNS
不存在。但是,如果我删除所有的 NS
和 null
,我无法使其正常工作。正确的方法是什么?对于不同的浏览器是否不同?