Controlling Scalable Vector Graphics (SVG) using Javascript

Articles —> Controlling Scalable Vector Graphics (SVG) using Javascript

Javascript can be used in combination with html graphical elements to produce graphics, charts, and diagrams. For instance an SVG element (or canvas element - not discussed here) can be used to draw or animate using javascript. SVG (Scalable Vector Graphics) is an XML language for use in rendering shapes and colors within a webpage and - at this time - is supported in most web browsers. A great advantage of using SVG is not only its ability to render very nice looking graphics, but also the ability to use javascript to change the SVG DOM: thus allowing user behavior to dynamically alter displayable SVG graphics.

As a simple demonstration, consider the following javascript code and html SVG element:

The javascript code:


/**

* Changes the color of the SVG rectangle with ID 'myrect'

*/

function doRectClick(){

   

    var myrect = document.getElementById('myrect');

   

    var r = Math.floor(Math.random() * 255);

    var g = Math.floor(Math.random() * 255);

    var b = Math.floor(Math.random() * 255);

    myrect.style.fill = 'rgb(' + r + ', ' + g + ' , ' + b + ')';

}

The html/SVG code:


<svg xmlns="http://www.w3.org/2000/svg" version="1.1">

  <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" id="myrect" onclick="doRectClick()" />

   <text x="60" y="40" fill="white" font-size="40" onclick="doRectClick();">Click Me</text>

</svg>

And the result: a simple rectangle which changes colors randomly based upon a mouse click.

Click Me

Click the rectangle to see it change color. (If you can't see the rectangle, your browser is not SVG compliant.)

Of course a simple rectangle is not that impressive. But a lot more can be done with SVG and javascript. For another simple example, how about rendering a bouncing ball - written in javascript and displayed with an SVG? The javascript code animates the ball using window.setInterval(), and alters the position of the ball on each frame based upon the current speed and the gravity and drag constants.

A bouncing ball animated with javascript using an SVG element to render the graphics. Can you catch the ball with a mouse click?

Great examples of using SVG graphics from within javascript can be found in the D3 library. The D3 library can be an extremely useful library for creating web based software to visualize data - be it a graph, chart, or diagram.



There are no comments on this article.

Back to Articles


© 2008-2022 Greg Cope