admin管理员组文章数量:1291032
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 = "";
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?
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/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?
- When I tried to replicate your problem I encountered that svgDocument was undefined. Any idea why thats happening? – Sayan Commented Oct 30, 2012 at 9:02
- I though html5 didn't required namespace anymore ?! – yota Commented Aug 21, 2017 at 16:30
1 Answer
Reset to default 9As far as I know createElementNS()
is part of the document
-variable, try:
var shape = document.createElementNS(svgns,"circle");
本文标签: javascriptHow to dynamically add an element to HTML5 SVGStack Overflow
版权声明:本文标题:javascript - How to dynamically add an element to HTML5 SVG? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741522074a2383247.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论