Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an svg element programmatically in an svg document?

Tags:

svg

I know that we can use the document.createElementNS("http://www.w3.org/2000/svg","line"); to create a svg element embeded in a html page.

But, this method doesn't seems to work in a standalone svg document.

Actually, I am trying to draw the national flag of India in svg, but, drawing the 24 spokes in the wheel of the flag would be very time consuming. So, I thought of drawing them programmatically through JavaScript.

Any help on how to create elements programmatically in a standalone svg document will be appreciated.

like image 871
Puspam Avatar asked Aug 31 '25 10:08

Puspam


1 Answers

You can use javascript inside an svg element. I've done only the center of the flag. Please observe the viewBox="-50 -50 100 100". The point {x:0,y:0} is in the center of the SVG canvas.

svg{border:1px solid; width:90vh;}
<svg viewBox="-50 -50 100 100" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" >
   
  <g id="center" fill="blue" stroke="blue">
  <circle r="5" />
  <circle id="outline" stroke-width="4" fill="none" r="48" />
  <polygon id="spoke" points="0,0 20,1.5 48,0 20,-1.5 0,0" fill="blue" stroke="none" />
  <circle id="dot" r="2.5" cx="46" transform="rotate(7.5)"  />
  </g>
  
    <script>
        <![CDATA[
const SVG_XLINK = "http://www.w3.org/1999/xlink";
const SVG_NS = 'http://www.w3.org/2000/svg';


// a function that creates a new `<use>` element and rotates it around the origin of the SVG canvas
function reuse(used,parent,i) {  
let use = document.createElementNS(SVG_NS, 'use');
use.setAttributeNS(SVG_XLINK, 'xlink:href', used); use.setAttributeNS(null,"transform" ,`rotate(${360*i/24})`);
parent.appendChild(use);
}
// a loop that creates 24 use elements
for(let i = 0;i < 24; i++ ){
reuse("#spoke",document.querySelector("#center"),i);
reuse("#dot",document.querySelector("#center"),i);
}
        ]]> 
  </script>
 
</svg>
like image 59
enxaneta Avatar answered Sep 05 '25 05:09

enxaneta