Basic SVG's with Javascript  

by ne on 2021-09-29 under Javascript

We all now are well aware of the extreme importance of a good client side portal for a website.
And how it's supremely powered by javascript and css.

But now a days a new concept is gaining strength. SVG.
Scalable Vector Graphics are fast, smooth and very attractive components that lure users to the webpage.

And they can be used wisely to create shapes, charts and much much more.

There are many libraries which will help you easily create and modify svg elements.

My personal favorite d3.js and snap.js.

Where d3 is much powerful, fully loaded javascript library capable of doing almost anything.

But if you wish to learn the basics, then here we go, with the main  motive of this blog post.

Creating SVG components with plain javascript.

 


var svg=document.createElementNS("http://www.w3.org/2000/svg", 'svg');
svg.setAttributes("height",h); 
svg.setAttributes("width",w); 
var circle=document.createElementNS("http://www.w3.org/2000/svg", 'circle');
circle.setAttributes("r",radius); 
circle.setAttributes("cx",x_of_center); 
circle.setAttributes("cy",y_of_center); 
circle.setAttributes("fill",'green'); 
svg.appendChild(circle);

The above code will make a circle with the attributes specified.

Now, when you will be using svg's on your page, then you will be needing a short hand function to do all the above.
Don't worry, I have provided a small-sized nice function for you:


function createShape(shape_,attributesJson) 
    { 
        var shape=document.createElementNS("http://www.w3.org/2000/svg", shape_);     
        var attr=JSON.parse(JSON.stringify(attributesJson)); 
        var keys=Object.keys(attr); 
        for(var i=0;i<keys.length;i++) { 
            var key=keys[i]; 
            shape.setAttribute(key,attr[key]); 
        } 
        return shape; 
    }

 


So, Now with pure javascript, you can create SVG's. For example the above task of creating a cirlce and appending it to the svg can
now be done as

 

 

 


var svg=createShape('svg',{'height':h,'width':w});
svg.appendChild(createShape('circle',{'r':radius,'cx':x_of_center,'cy':y_of_center});

 


More on svgs with javascript later.
Hope you enjoyed.. :)
And if you did, don't forget to upvote this post.