SVG circle not drawn using javascript

I am trying to make a hello world for svg manipulation using javascript in HTML. I wrote the code below, and although it generates the correct html, I do not see any output in the browser and I see no 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 mistaken? thanks in advance.

+6
source share
1 answer

SVG elements must be created using the SVG XML namespace. You can do this 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> 
+21
source

Source: https://habr.com/ru/post/955620/


All Articles