JS: Scripting SVG, Basic Example

By Xah Lee. Date: . Last updated: .

This page is a tutorial on creating SVG using JavaScript.

Here's a SVG image, created by JavaScript.

Here's the HTML code:

<div id="svg54583"></div>

Here's JavaScript:

(function() {

    // create a svg tag
    var svg_container = document.createElementNS("http://www.w3.org/2000/svg", "svg");

    // set width and height of the svg view port
    svg_container.setAttribute("width", "100");
    svg_container.setAttribute("height", "100");

    // create a circle
    var my_circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    my_circle.setAttribute("cx", "80"); // x coordinate for center
    my_circle.setAttribute("cy", "80"); // y coordinate for center
    my_circle.setAttribute("r", "30");  // radius
    my_circle.setAttribute("fill", "#22ee77"); // fill color

    // attach it to the container
    svg_container.appendChild(my_circle);

    // attach container to document
    document.getElementById("svg54583").appendChild(svg_container);

})();

How to Script SVG?

Rememer that SVG is just XML. So, to script SVG, you don't have to do anything special. Just use JavaScript to script normal XML.

Here's what you need to do.

  1. Use “createElementNS” to create a SVG element (the SVG “container”, called view port.).
  2. Use “createElementNS” to create SVG drawing elements (For example, circle, rect, path, ….).
  3. Attach drawing elements to the SVG element.
  4. Attach the SVG element to the document.

You need to know what are the available drawing elements, their tag names and attributes. For a basic intro, see: SVG: Basic Examples.

You also need to have a basic experience of JavaScript and DOM, see:

Reference

Scripting – SVG 1.1 (Second Edition)

Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth