Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svg circle not being drawn with javascript

I have been trying to do a hello world for svg manipulation using javascript in HTML. I have written the below code and although it generates the correct html, I don't see any output in the browser, nor do I see any error.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElement("svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElement("circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

Where am I going wrong? thanks in advance.

like image 400
Abdul Khader Avatar asked Oct 09 '13 19:10

Abdul Khader


1 Answers

SVG elements need to be created with the SVG XML namespace. You can do that using createElementNS and using the http://www.w3.org/2000/svg namespace:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>
like image 127
zneak Avatar answered Nov 15 '22 14:11

zneak