如何动态添加元素到 HTML5 SVG?
我读过一些与此类似的问题,但我无法让我的代码正常工作。我想在用户单击 SVG 区域时添加 SVG 元素。
这是我的带有 SVG 的 HTML5,它可以正确呈现:
<!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
,我也无法让它工作。这样做的正确方法是什么?不同浏览器有不同吗?
I have read a few questions similar to this, but I can't get my code working properly. I want to add a SVG element when a the user click on the SVG-area.
Here is my HTML5 with SVG, it renders correctly:
<!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>
Here is the JavaScript that is executed on a click event:
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);
In Google Chrome I get an error message that createElementNS
doesn't exist. But I can't get it working if I remove all NS
and null
either. What is the correct way to do this? Is is different for different browsers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知
createElementNS()
是document
变量的一部分,请尝试:As far as I know
createElementNS()
is part of thedocument
-variable, try: