Sometimes, we want to create SVG graphics using JavaScript.
In this article, we’ll look at how to create SVG graphics using JavaScript.
How to create SVG graphics using JavaScript?
To create SVG graphics using JavaScript, we can use the createElementNS and setAttributeNS methods.
For instance, we write
const svgNs = "http://www.w3.org/2000/svg";
const shape = document.createElementNS(svgNs, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
to call document.createElementNS to create a circle element with the svgNs namespace.
Then we call shape.setAttributeNS to add the cx, cy, r and fill attributes to the shape circle element and set them to values in the 3rd argument.
Conclusion
To create SVG graphics using JavaScript, we can use the createElementNS and setAttributeNS methods.
