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?
As far as I know createElementNS()
is part of the document
-variable, try:
var shape = document.createElementNS(svgns,"circle");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With