SVG.js

Getting started

Preparation

Create a basic Html markup and include the svg.js script:

<!DOCTYPE html>
<html>
<head>
  <title>SVG.js</title>
  <script src="https://cdn.jsdelivr.net/npm/@svgdotjs/svg.js@3.0/dist/svg.min.js"></script>
</head>
<body>

</body>
</html>

Or just import svg.js in your javascript application:

import { SVG } from '@svgdotjs/svg.js'

Note: All properties that were former available on the global SVG object need to be imported now, see example below:

import { SVG, extend as SVGextend, Element as SVGElement } from '@svgdotjs/svg.js'

Create an SVG document

Next, use the SVG() function to create an SVG document and add it to the html page:

var draw = SVG().addTo('body').size(300, 300)
var rect = draw.rect(100, 100).attr({ fill: '#f06' })

You can pass any css selector to addTo or simply a node.

<body>
  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
    <rect width="100" height="100" fill="#f06"></rect>
  </svg>
</body>

SVG.js does not set a size for the document automatically. So make sure to call size() with appropriate values.
E.g. to set the size to the dimensions of its parent use this:

var draw = SVG().addTo('#someId').size('100%', '100%')

Wait for DOM to be loaded

This might seem obvious to many but it's still worth mentioning. If you include your js files in the head of your document, make sure to wait for the DOM to be loaded:

SVG.on(document, 'DOMContentLoaded', function() {
  var draw = SVG().addTo('body')
})

This is not an issue if you include your js at the bottom.

Pure SVG

SVG.js also works outside of the HTML DOM, inside an SVG document for example:

<?xml version="1.0" encoding="utf-8" ?>
<svg id="drawing" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" >
  <script type="text/javascript" xlink:href="svg.min.js"></script>
  <script type="text/javascript">
    <![CDATA[
      var draw = SVG('#drawing')
      draw.rect(100,100).animate().fill('#f03').move(100,100)
    ]]>
  </script>
</svg>

The SVG() function

This function does not only create new documents, it can also retrieve svg.js objects from the dom or create new ones from an svg fragment:

// new document
var draw = SVG()

// get rect from dom
var rect = SVG('#myRectId')
// or
var rect = SVG('rect')
// any css selector will do
var path = SVG('#group1 path.myClass')

// create new object from fragment
var circle = SVG('<circle>')

// convert node to svg.js object
var obj = SVG(node)

Playground

Just to get you going, here is a basic setup. Everything is present to start fiddling.

Fork me on GitHub