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:

{

const f = (() => {

    // create the svg element
    const svg_box = document.createElementNS("http://www.w3.org/2000/svg", "svg");

    // set width and height
    svg_box.setAttribute("width", "100");
    svg_box.setAttribute("height", "100");

    // create a circle
    const my_circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    my_circle.setAttribute("cx", "80");
    my_circle.setAttribute("cy", "80");
    my_circle.setAttribute("r", "30");
    my_circle.setAttribute("fill", "red");

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

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

});

f()
;

}

Here's pre ES2015 version:

"use strict";
{
    var f = (function () {
        // create the svg element
        var svg_box = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        // set width and height
        svg_box.setAttribute("width", "100");
        svg_box.setAttribute("height", "100");
        // create a circle
        var my_circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
        my_circle.setAttribute("cx", "80");
        my_circle.setAttribute("cy", "80");
        my_circle.setAttribute("r", "30");
        my_circle.setAttribute("fill", "red");
        // attach it to the container
        svg_box.appendChild(my_circle);
        // attach container to document
        document.getElementById("svg54583").appendChild(svg_box);
    });
    f();
}

How to Script SVG?

Rememer that SVG is just XML. (and XML is like XML but with more strict syntax) 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.
  2. Use “createElementNS” to create SVG shape elements (For example, circle, rect, path, ….).
  3. Attach shape elements to the SVG element.
  4. Attach the SVG element to the document.

You need to know what are the available shape 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)

SVG Topics

  1. SVG: Basic Examples
  2. SVG Path Tutorial
  3. SVG Path: Elliptical Arc
  4. SVG: Specifying Styles
  5. SVG: Basic Shape Styles
  6. SVG: Viewport
  7. SVG: viewBox, User Coordinate
  8. SVG: Coordinate Transformation
  9. SVG: Text Element Tutorial
  10. SVG: Structure Elements
  11. JS: Scripting SVG, Basic Example
  12. JS: SVG Clock
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon