Fork me on GitHub


A lightweight library for manipulating and animating SVG.

Svg.js has no dependencies and aims to be as small as possible.

Svg.js is licensed under the terms of the MIT License.

See for an introduction, documentation and some action.


Create an SVG document

Use the SVG() function to create an SVG document within a given html element:

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

The first argument can either be an id of the element or the selected element itself.
This will generate the following output:

<div id="drawing">
    <svg xmlns="" version="1.1" xmlns:xlink="" width="300" height="300">
        <rect width="100" height="100" fill="#f06"></rect>

By default the svg drawing follows the dimensions of its parent, in this case #drawing:

var draw = SVG('drawing').size('100%', '100%')

Checking for SVG support

By default this library assumes the client's browser supports SVG. You can test support as follows:

if (SVG.supported) {
  var draw = SVG('drawing')
  var rect = draw.rect(100, 100)
} else {
  alert('SVG not supported')

SVG document

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="" xmlns:xlink="" version="1.1" >
  <script type="text/javascript" xlink:href="svg.min.js"></script>
  <script type="text/javascript">
      var draw = SVG('drawing')

Sub-pixel offset fix

Call the spof() method to fix sub-pixel offset:

var draw = SVG('drawing').spof()

To enable automatic sub-pixel offset correction when the window is resized:

SVG.on(window, 'resize', function() { draw.spof() })

Parent elements

Main svg document

The main SVG.js initializer function creates a root svg node in the given element and returns an instance of SVG.Doc:

var draw = SVG('drawing')

returns: SVG.Doc

Javascript inheritance stack: SVG.Doc < SVG.Container < SVG.Parent

Nested svg

With this feature you can nest svg documents within each other. Nested svg documents have exactly the same features as the main, top-level svg document:

var nested = draw.nested()

var rect = nested.rect(200, 200)

returns: SVG.Nested

Javascript inheritance stack: SVG.Nested < SVG.Container < SVG.Parent


Grouping elements is useful if you want to transform a set of elements as if it were one. All element within a group maintain their position relative to the group they belong to. A group has all the same element methods as the root svg document:

var group =

Existing elements from the svg document can also be added to a group:


Note: Groups do not have a geometry of their own, it's inherited from their content. Therefore groups do not listen to x, y, width and height attributes. If that is what you are looking for, use a nested() svg instead.

returns: SVG.G

Javascript inheritance stack: SVG.G < SVG.Container < SVG.Parent


A hyperlink or <a> tag creates a container that enables a link on all children:

var link ='')
var rect = link.rect(100, 100)

The link url can be updated with the to() method:'')

Furthermore, the link element has a show() method to create the xlink:show attribute:'replace')

And the target() method to create the target attribute:'_blank')

Elements can also be linked the other way around with the linkTo() method:


Alternatively a block can be passed instead of a url for more options on the link element:

rect.linkTo(function(link) {'').target('_blank')

returns: SVG.A

Javascript inheritance stack: SVG.A < SVG.Container < SVG.Parent


The <defs> element is a container element for referenced elements. Elements that are descendants of a ‘defs’ are not rendered directly. The <defs> node lives in the main <svg> document and can be accessed with the defs() method:

var defs = draw.defs()

The defs are also available on any other element through the doc() method:

var defs = rect.doc().defs()

The defs node works exactly the same as groups.

returns: SVG.Defs

Javascript inheritance stack: SVG.Defs < SVG.Container < SVG.Parent


Rects have two arguments, their width and height:

var rect = draw.rect(100, 100)

returns: SVG.Rect

Javascript inheritance stack: SVG.Rect < SVG.Shape < SVG.Element


Rects can also have rounded corners:


This will set the rx and ry attributes to 10. To set rx and ry individually:

rect.radius(10, 20)

returns: itself


The only argument necessary for a circle is the diameter:

var circle =

returns: SVG.Circle

Javascript inheritance stack: SVG.Circle < SVG.Shape < SVG.Element


Circles can also be redefined by their radius:


returns: itself


Ellipses, like rects, have two arguments, their width and height:

var ellipse = draw.ellipse(200, 100)

returns: SVG.Ellipse

Javascript inheritance stack: SVG.Ellipse < SVG.Shape < SVG.Element


Ellipses can also be redefined by their radii:

rect.radius(75, 50)

returns: itself


Create a line from point A to point B:

var line = draw.line(0, 0, 100, 150).stroke({ width: 1 })

Creating a line element can be done in four ways. Look at the plot() method to see all the possiblilities.

returns: SVG.Line

Javascript inheritance stack: SVG.Line < SVG.Shape < SVG.Element


Updating a line is done with the plot() method:

line.plot(50, 30, 100, 150)

Alternatively it also accepts a point string:

line.plot('0,0 100,150')

Or a point array:

line.plot([[0, 0], [100, 150]])

Or an instance of SVG.PointArray:

var array = new SVG.PointArray([[0, 0], [100, 150]])

returns: itself


References the SVG.PointArray instance. This method is rather intended for internal use:


returns: SVG.PointArray


The polyline element defines a set of connected straight line segments. Typically, polyline elements define open shapes:

// polyline('x,y x,y x,y')
var polyline = draw.polyline('0,0 100,50 50,100').fill('none').stroke({ width: 1 })

Polyline strings consist of a list of points separated by spaces: x,y x,y x,y.

As an alternative an array of points will work as well:

// polyline([[x,y], [x,y], [x,y]])
var polyline = draw.polyline([[0,0], [100,50], [50,100]]).fill('none').stroke({ width: 1 })

returns: SVG.Polyline

Javascript inheritance stack: SVG.Polyline < SVG.Shape < SVG.Element


Polylines can be updated using the plot() method:

polyline.plot([[0,0], [100,50], [50,100], [150,50], [200,50]])

The plot() method can also be animated:

polyline.animate(3000).plot([[0,0], [100,50], [50,100], [150,50], [200,50], [250,100], [300,50], [350,50]])

returns: itself


References the SVG.PointArray instance. This method is rather intended for internal use:


returns: SVG.PointArray


The polygon element, unlike the polyline element, defines a closed shape consisting of a set of connected straight line segments:

// polygon('x,y x,y x,y')
var polygon = draw.polygon('0,0 100,50 50,100').fill('none').stroke({ width: 1 })

Polygon strings are exactly the same as polyline strings. There is no need to close the shape as the first and last point will be connected automatically.

returns: SVG.Polygon

Javascript inheritance stack: SVG.Polygon < SVG.Shape < SVG.Element


Like polylines, polygons can be updated using the plot() method:

polygon.plot([[0,0], [100,50], [50,100], [150,50], [200,50]])

The plot() method can also be animated:

polygon.animate(3000).plot([[0,0], [100,50], [50,100], [150,50], [200,50], [250,100], [300,50], [350,50]])

returns: itself


References the SVG.PointArray instance. This method is rather intended for internal use:


returns: SVG.PointArray


The path string is similar to the polygon string but much more complex in order to support curves:

draw.path('M 100 200 C 200 100 300  0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100')

returns: SVG.Path

Javascript inheritance stack: SVG.Path < SVG.Shape < SVG.Element

For more details on path data strings, please refer to the SVG documentation:


Paths can be updated using the plot() method:


returns: itself


References the SVG.PathArray instance. This method is rather intended for internal use:


returns: SVG.PathArray


Creating images is as you might expect:

var image = draw.image('/path/to/image.jpg')

If you know the size of the image, those parameters can be passed as the second and third arguments:

var image = draw.image('/path/to/image.jpg', 200, 300)

returns: SVG.Image

Javascript inheritance stack: SVG.Image < SVG.Shape < SVG.Element


Loading another image can be done with the load() method:


returns: itself


If you don't know the size of the image, obviously you will have to wait for the image to be loaded:

var image = draw.image('/path/to/image.jpg').loaded(function(loader) {
  this.size(loader.width, loader.height)

The returned loader object as first the argument of the loaded method contains four values:

returns: itself


Unlike html, text in svg is much harder to tame. There is no way to create flowing text, so newlines should be entered manually. In SVG.js there are two ways to create text elements.

The first and easiest method is to provide a string of text, split by newlines:

var text = draw.text("Lorem ipsum dolor sit amet consectetur.\nCras sodales imperdiet auctor.")

This will automatically create a block of text and insert newlines where necessary.

The second method will give you much more control but requires a bit more code:

var text = draw.text(function(add) {
  add.tspan('Lorem ipsum dolor sit amet ').newLine()
  add.tspan('Cras sodales imperdiet auctor.').newLine().dx(20)
  add.tspan('Nunc ultrices lectus at erat').newLine()
  add.tspan('dictum pharetra elementum ante').newLine()

If you want to go the other way and don't want to add tspans at all, just one line of text, you can use the plain() method instead:

var text = draw.plain('Lorem ipsum dolor sit amet consectetur.')

This is a shortcut to the plain method on the SVG.Text instance which doesn't render newlines at all.

Javascript inheritance stack: SVG.Text < SVG.Shape < SVG.Element

returns: SVG.Text


Changing text afterwards is also possible with the text() method:


returns: itself

To get the raw text content:


returns: string


Just adding one tspan is also possible:

text.tspan(' on a train...').fill('#f06')

returns: SVG.Tspan


If the content of the element doesn't need any stying or multiple lines, it might be sufficient to just add some plain text:

text.plain('I do not have any expectations.')

returns: itself


The sugar.js module provides some syntax sugar specifically for this element type:

  family:   'Helvetica'
, size:     144
, anchor:   'middle'
, leading:  '1.5em'

returns: itself


As opposed to html, where leading is defined by line-height, svg does not have a natural leading equivalent. In svg, lines are not defined naturally. They are defined by <tspan> nodes with a dy attribute defining the line height and a x value resetting the line to the x position of the parent text element. But you can also have many nodes in one line defining a different y, dy, x or even dx value. This gives us a lot of freedom, but also a lot more responsibility. We have to decide when a new line is defined, where it starts, what its offset is and what it's height is. The leading() method in SVG.js tries to ease the pain by giving you behaviour that is much closer to html. In combination with newline separated text, it works just like html:

var text = draw.text("Lorem ipsum dolor sit amet consectetur.\nCras sodales imperdiet auctor.")

This will render a text element with a tspan element for each line, with a dy value of 130% of the font size.

Note that the leading() method assumes that every first level tspan in a text node represents a new line. Using leading() on text elements containing multiple tspans in one line (e.g. without a wrapping tspan defining a new line) will render scrambeled. So it is advisable to use this method with care, preferably only when throwing newline separated text at the text element or calling the newLine() method on every first level tspan added in the block passed as argument to the text element.

returns: itself


The build() can be used to enable / disable build mode. With build mode disabled, the plain() and tspan() methods will first call the clear() bethod before adding the new content. So when build mode is enabled, plain() and tspan() will append the new content to the existing content. When passing a block to the text() method, build mode is toggled automatically before and after the block is called. But in some cases it might be useful to be able to toggle it manually:

var text = draw.text('This is just the start, ')  // enables build mode

var tspan = text.tspan('something pink in the middle ').fill('#00ff97')
text.plain('and again boring at the end.') // disables build mode


returns: itself


This is an internal callback that probably never needs to be called manually. Basically it rebuilds the text element whenerver font-size and x attributes or the leading() of the text element are modified. This method also acts a setter to enable or disable rebuilding:

text.rebuild(false) //-> disables rebuilding
text.rebuild(true)  //-> enables rebuilding and instantaneously rebuilds the text element

returns: itself


Clear all the contents of the called text element:


returns: itself


Gets the total computed text length of all tspans together:


returns: number


All first level tspans can be referenced with the lines() method:


This will return an intance of SVG.Set including all tspan elements.

returns: SVG.Set


The text element has one event. It is fired every time the rebuild() method is called:

text.on('rebuild', function() {
  // whatever you need to do after rebuilding


The tspan elements are only available inside text elements or inside other tspan elements. In SVG.js they have a class of their own:

Javascript inheritance stack: SVG.Tspan < SVG.Shape < SVG.Element


Update the content of the tspan. This can be done by either passing a string:

tspan.text('Just a string.')

Which will basicly call the plain() method.

Or by passing a block to add more specific content inside the called tspan:

tspan.text(function(add) {
  add.plain('Just plain text.')
  add.tspan('Fancy text wrapped in a tspan.').fill('#f06')
  add.tspan(function(addMore) {
    addMore.tspan('And you can doo deeper and deeper...')

returns: itself


Add a nested tspan:

tspan.tspan('I am a child of my parent').fill('#f06')

returns: SVG.Tspan


Just adds some plain text:

tspan.plain('I do not have any expectations.')

returns: itself


Define the dynamic x value of the element, much like a html element with position:relative and left defined:


returns: itself


Define the dynamic y value of the element, much like a html element with position:relative and top defined:


returns: itself


The newLine() is a convenience method for adding a new line with a dy attribute using the current "leading":

var text = draw.text(function(add) {
  add.tspan('Lorem ipsum dolor sit amet ').newLine()
  add.tspan('Cras sodales imperdiet auctor.').newLine().dx(20)
  add.tspan('Nunc ultrices lectus at erat').newLine()
  add.tspan('dictum pharetra elementum ante').newLine()

returns: itself


Clear all the contents of the called tspan element:


returns: itself


Gets the total computed text length:


returns: number


A nice feature in svg is the ability to run text along a path:

var text = draw.text(function(add) {
  add.tspan('We go ')
  add.tspan(', then we go down, then up again').dy(40)
  .path('M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100')
  .font({ size: 42.5, family: 'Verdana' })

When calling the path() method on a text element, the text element is mutated into an intermediate between a text and a path element. From that point on the text element will also feature a plot() method to update the path:

text.plot('M 300 500 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100')

Attributes specific to the <textPath> element can be applied to the textPath instance itself:

text.textPath().attr('startOffset', 0.5)

And they can be animated as well of course:

text.textPath().animate(3000).attr('startOffset', 0.8)

returns: SVG.TextPath

Javascript inheritance stack: SVG.TextPath < SVG.Element


Referencing the textPath node directly:

var textPath = text.textPath()

returns: SVG.TextPath


Referencing the linked path element directly:

var path = text.track()

returns: SVG.Path


The use element simply emulates another existing element. Any changes on the master element will be reflected on all the use instances. The usage of use() is very straightforward:

var rect = draw.rect(100, 100).fill('#f09')
var use  = draw.use(rect).move(200, 200)

In the case of the example above two rects will appear on the svg drawing, the original and the use instance. In some cases you might want to hide the original element. the best way to do this is to create the original element in the defs node:

var rect = draw.defs().rect(100, 100).fill('#f09')
var use  = draw.use(rect).move(200, 200)

In this way the rect element acts as a library element. You can edit it but it won't be rendered.

Another way is to point an external SVG file, just specified the element id and path to file.

var use  = draw.use('elementId', 'path/to/file.svg')

This way is usefull when you have complex images already created.
Note that, for external images (outside your domain) it may be necessary to load the file with XHR.

returns: SVG.Use

Javascript inheritance stack: SVG.Use < SVG.Shape < SVG.Element


Not unlike the group element, the symbol element is a container element. The only difference between symbols and groups is that symbols are not rendered. Therefore a symbol element is ideal in combination with the use element:

var symbol = draw.symbol()
symbol.rect(100, 100).fill('#f09')

var use  = draw.use(symbol).move(200, 200)

returns: SVG.Bare

Javascript inheritance stack: SVG.Bare < SVG.Element [with a shallow inheritance from SVG.Parent]


For all SVG elements that are not described by SVG.js, the SVG.Bare class comes in handy. This class inherits directly from SVG.Element and makes it possible to add custom methods in a separate namespace without polluting the main SVG.Element namespace. Consider it your personal playground.


The SVG.Bare class can be instantiated with the element() method on any parent element:

var element = draw.element('title')

The string value passed as the first argument is the node name that should be generated.

Additionally any existing class name can be passed as the second argument to define from which class the element should inherit:

var element = draw.element('symbol', SVG.Parent)

This gives you as the user a lot of power. But remember, with great power comes great responsibility.

returns: SVG.Bare


The SVG.Bare instance carries an additional method to add plain text:

var element = draw.element('title').words('This is a title.')
//-> <title>This is a title.</title>

returns: itself

Referencing elements

By id

If you want to get an element created by SVG.js by its id, you can use the SVG.get() method:

var element = SVG.get('my_element')


Using CSS selectors

There are two ways to select elements using CSS selectors.

The first is to search globally. This will search in all svg elements in a document and return them in an instance of SVG.Set:

var elements ='').fill('#f06')

The second is to search within a parent element:

var elements ='').fill('#f06')

Using jQuery or Zepto

Another way is to use jQuery or Zepto. Here is an example:

/* add elements */
var draw   = SVG('drawing')
var group  ='my-group')
var rect   = group.rect(100,100).addClass('my-element')
var circle ='my-element').move(100, 100)

/* get elements in group */
var elements = $('#drawing .my-element').each(function() {

Circular reference

Every element instance within SVG.js has a reference to the actual node:



returns: node


The same can be achieved with the native() method:


returns: node


Similar, the node carries a reference to the SVG.js instance:


returns: element

Parent reference

Every element has a reference to its parent with the parent() method:



returns: element

Even the main svg document:

var draw = SVG('drawing')

draw.parent() //-> returns the wrappig html element with id 'drawing'

returns: HTMLNode


For more specific parent filtering the doc() method can be used:

var draw = SVG('drawing')
var rect = draw.rect(100, 100)

rect.doc() //-> returns draw

Alternatively a class can be passed as the first argument:

var draw   = SVG('drawing')
var nested = draw.nested()
var group  =
var rect   = group.rect(100, 100)

rect.doc()           //-> returns draw
rect.doc(SVG.Doc)    //-> returns draw
rect.doc(SVG.Nested) //-> returns nested
rect.doc(SVG.G)      //-> returns group

returns: element

Child references


To get the first child of a parent element:


returns: element


To get the last child of a parent element:


returns: element


An array of all children will can be retreives with the children method:


returns: array


The each() allows you to iterate over the all children of a parent element:

draw.each(function(i, children) {
  this.fill({ color: '#f06' })

Deep traversing is also possible by passing true as the second argument:

// draw.each(block, deep)
draw.each(function(i, children) {
  this.fill({ color: '#f06' })
}, true)

Note that this refers to the current child element.

returns: itself


Checking the existence of an element within a parent:

var rect  = draw.rect(100, 50)
var group =

draw.has(rect)  //-> returns true
group.has(rect) //-> returns false

returns: boolean


Returns the index of given element and returns -1 when it is not a child:

var rect  = draw.rect(100, 50)
var group =

draw.index(rect)  //-> returns 0
group.index(rect) //-> returns -1

returns: number


Get an element on a given position in the children array:

var rect   = draw.rect(20, 30)
var circle =

draw.get(0) //-> returns rect
draw.get(1) //-> returns circle

returns: element


To remove all elements from a parent element:


returns: itself

Attribute references


In cases where an element is linked to another element through an attribute, the linked element instance can be fetched with the reference() method. The only thing required is the attribute name:

use.reference('href') //-> returns used element instance
// or
rect.reference('fill') //-> returns gradient or pattern instance for example
// or
circle.reference('clip-path') //-> returns clip instance

Import / export SVG


Exporting the full generated SVG, or a part of it, can be done with the svg() method:


Exporting works on all elements.

Importing is done with the same method:

draw.svg('<g><rect width="100" height="50" fill="#f06"></rect></g>')

Importing works on any element that inherits from SVG.Parent, which is basically every element that can contain other elements.

getterreturns: string

setterreturns: itself

Manipulating elements


You can get and set an element's attributes directly using attr().

Get a single attribute:


Set a single attribute:

rect.attr('x', 50)

Set multiple attributes at once:

  fill: '#f06'
, 'fill-opacity': 0.5
, stroke: '#000'
, 'stroke-width': 10

Set an attribute with a namespace:

rect.attr('x', 50, '')

Explicitly remove an attribute:

rect.attr('fill', null)

getterreturns: value

setterreturns: itself


The transform() method acts as a full getter without an argument:


The returned object contains the following values:

Additionally a string value for the required property can be passed:


In this case the returned value is a number.

As a setter it has two ways of working. By default transformations are absolute. For example, if you call:

element.transform({ rotation: 125 }).transform({ rotation: 37.5 })

The resulting rotation will be 37.5 and not the sum of the two transformations. But if that's what you want there is a way out by adding the relative parameter. That would be:

element.transform({ rotation: 125 }).transform({ rotation: 37.5, relative: true })

Alternatively a relative flag can be passed as the second argument:

element.transform({ rotation: 125 }).transform({ rotation: 37.5 }, true)

Available transformations are:

getterreturns: value

setterreturns: itself


With the style() method the style attribute can be managed like attributes with attr:'cursor', 'pointer')

Multiple styles can be set at once using an object:{ cursor: 'pointer', fill: '#f03' })

Or a css string:'cursor:pointer;fill:#f03;')

Similar to attr() the style() method can also act as a getter:'cursor')
// => pointer

Or even a full getter:
// => 'cursor:pointer;fill:#f03;'

Explicitly deleting individual style definitions works the same as with the attr() method:'cursor', null)

getterreturns: value

setterreturns: itself


Fetches an array of css classes on the node:


getterreturns: array


Test the presence of a given css class:


getterreturns: boolean


Adds a given css class:


setterreturns: itself


Removes a given css class:


setterreturns: itself


Toggles a given css class:


setterreturns: itself


Move the element to a given x and y position by its upper left corner:

rect.move(200, 350)

Note that you can also use the following code to move some elements (like images and rects) around:

rect.attr({ x: 20, y: 60 })

Although move() is much more convenient because it will always use the upper left corner as the position reference, whereas with using attr() the x and y reference differ between element types. For example, rect uses the upper left corner with the x and y attributes, circle and ellipse use their center with the cx and cy attributes and thereby simply ignoring the x and y values you might assign.

returns: itself


Move element only along x-axis by its upper left corner:


Without an argument the x() method serves as a getter as well:

rect.x() //-> returns 200

getterreturns: value

setterreturns: itself


Move element only along y-axis by its upper left corner:


Without an argument the y() method serves as a getter as well:

rect.y() //-> returns 350

getterreturns: value

setterreturns: itself


Move the element to a given x and y position relative to its current position:

rect.dmove(10, 30)

returns: itself


Move element only along x-axis relative to its current position:


returns: itself


Move element only along y-axis relative to its current position:


returns: itself


This is an extra method to move an element by its center:, 150)

returns: itself


Move element only along x-axis by its center:

Without an argument the cx() method serves as a getter as well: //-> returns 200

getterreturns: value

setterreturns: itself


Move element only along y-axis by its center:

Without an argument the cy() method serves as a getter as well: //-> returns 350

getterreturns: value

setterreturns: itself


Set the size of an element by a given width and height:

rect.size(200, 300)

Proportional resizing is also possible by leaving out height:


Or by passing null as the value for width:

rect.size(null, 200)

Same as with move() the size of an element could be set by using attr(). But because every type of element is handles its size differently the size() method is much more convenient.

There is one exceptions though, the SVG.Text only takes one argument and applies the given value to the font-size attribute.

returns: itself


Set only width of an element:


This method also acts as a getter:

rect.width() //-> returns 200

getterreturns: value

setterreturns: itself


Set only height of an element:


This method also acts as a getter:

rect.height() //-> returns 325

getterreturns: value

setterreturns: itself


Hide element:


returns: itself


Show element:

returns: itself


To check if the element is visible:


returns: boolean


To make an exact copy of an element the clone() method comes in handy:

var clone = rect.clone()

returns: element

This will create an new, unlinked copy. If you want to make a linked clone have a look at the use element.


Pretty straightforward:


returns: itself


This method will replace the called element with the given element in the same position in the stack:


returns: element

Inserting elements


Elements can be moved between parents via the add() method on any parent:

var rect = draw.rect(100, 100)
var group =

group.add(rect) //-> returns group

returns: itself


Where the add() method returns the parent itself, the put() method returns the given element:

group.put(rect) //-> returns rect

returns: element


Similar to the add() method on a parent element, elements have the addTo() method:

rect.addTo(group) //-> returns rect

returns: itself


Similar to the put() method on a parent element, elements have the putIn() method:

rect.putIn(group) //-> returns group

returns: element



The viewBox attribute of an <svg> element can be managed with the viewbox() method. When supplied with four arguments it will act as a setter:

draw.viewbox(0, 0, 297, 210)

Alternatively you can also supply an object as the first argument:

draw.viewbox({ x: 0, y: 0, width: 297, height: 210 })

Without any arguments an instance of SVG.ViewBox will be returned:

var box = draw.viewbox()

But the best thing about the viewbox() method is that you can get the zoom of the viewbox:

var box = draw.viewbox()
var zoom = box.zoom

If the size of the viewbox equals the size of the svg drawing, the zoom value will be 1.

getterreturns: SVG.ViewBox

setterreturns: itself


Get the bounding box of an element. This is a wrapper for the native getBBox() method but adds more values:


This will return an instance of SVG.BBox containing the following values:

The SVG.BBox has one other nifty little feature, enter the merge() method. With merge() two SVG.BBox instances can be merged into one new instance, basically being the bounding box of the two original bounding boxes:

var box1 = draw.rect(100,100).move(50,50)
var box2 = draw.rect(100,100).move(200,200)
var box3 = box1.merge(box2)

returns: SVG.BBox


Where bbox() returns a bounding box mindless of any transformations, the tbox() method does take transformations into account. So any translation or scale will be applied to the resulting values to get closer to the actual visual representation:


This will return an instance of SVG.TBox containing the following values:

Note that the rotation of the element will not be added to the calculation.

returns: SVG.TBox


Is similar to bbox() but will give you the box around the exact visual representation of the element, taking all transformations into account.


This will return an instance of SVG.RBox containing the following values:

Important: Mozilla browsers include stroke widths where other browsers do not. Therefore the resulting box might be different in Mozulla browsers. It is very hard to modify this behavior so for the time being this is an inconvenience we have to live with.

returns: SVG.RBox


Retreives the current transform matrix of the element:


returns: SVG.Matrix


To check if a given point is inside the bounding box of an element you can use the inside() method:

var rect = draw.rect(100, 100).move(50, 50)

rect.inside(25, 30) //-> returns false
rect.inside(60, 70) //-> returns true

Note: the x and y positions are tested against the relative position of the element. Any offset on the parent element is not taken into account.

returns: boolean


Get the total length of a path element:

var length = path.length()

returns: number


Get point on a path at given length:

var point = path.pointAt(105) //-> returns { x : 96.88497924804688, y : 58.062747955322266 }

returns: object

Animating elements

Animatable method chain

Note that the animate() method will not return the targeted element but an instance of SVG.FX which will take the following methods:

Of course attr():

rect.animate().attr({ fill: '#f03' })

The x(), y() and move() methods:

rect.animate().move(100, 100)

And the cx(), cy() and center() methods:

rect.animate().center(200, 200)

If you include the sugar.js module, fill(), stroke(), rotate(), skew(), scale(), matrix(), opacity(), radius() will be available as well:

rect.animate().rotate(45).skew(25, 0)

You can also animate non-numeric unit values using the attr() method:

rect.attr('x', '10%').animate().attr('x', '50%')


All available ease types are:

For the latter, here is an example of the default <> function:

function(pos) { return (-Math.cos(pos * Math.PI) / 2) + 0.5 }

For more easing equations, have a look at the svg.easing.js plugin.


Animating elements is very much the same as manipulating elements, the only difference is you have to include the animate() method:

rect.animate().move(150, 150)

The animate() method will take three arguments. The first is duration, the second ease and the third delay:

rect.animate(2000, '>', 1000).attr({ fill: '#f03' })

Alternatively you can pass an object as the first argument:

rect.animate({ ease: '<', delay: '1.5s' }).attr({ fill: '#f03' })

By default duration will be set to 1000, ease will be set to <>.

returns: SVG.FX


Pausing an animations is fairly straightforward:

rect.animate().move(200, 200)

rect.mouseover(function() { this.pause() })

returns: itself


Will start playing a paused animation:

rect.animate().move(200, 200)

rect.mouseover(function() { this.pause() })
rect.mouseout(function() { })

returns: itself


Animations can be stopped in two ways.

By calling the stop() method:

rect.animate().move(200, 200)


Or by invoking another animation:

rect.animate().move(200, 200)

rect.animate().center(200, 200)

By calling stop(), the transition is left at its current position. By passing true as the first argument to stop(), the animation will be fulfilled instantly:

rect.animate().move(200, 200)


Stopping an animation is irreversable.

returns: itself


If you want to perform your own actions during the animations you can use the during() method:

var position
  , from = 100
  , to   = 300

rect.animate(3000).move(100, 100).during(function(pos) {
  position = from + (to - from) * pos 

Note that pos is 0 in the beginning of the animation and 1 at the end of the animation.

To make things easier a morphing function is passed as the second argument. This function accepts a from and to value as the first and second argument and they can be a number, unit or hex color:

var ellipse = draw.ellipse(100, 100).attr('cx', '20%').fill('#333')

rect.animate(3000).move(100, 100).during(function(pos, morph) {
  // numeric values
  ellipse.size(morph(100, 200), morph(100, 50))

  // unit strings
  ellipse.attr('cx', morph('20%', '80%'))

  // hex color strings
  ellipse.fill(morph('#333', '#ff0066'))

returns: SVG.FX


By default the loop() method creates and eternal loop:

rect.animate(3000).move(100, 100).loop()

But the loop can also be a predefined number of times:

rect.animate(3000).move(100, 100).loop(3)

Loops go from beginning to end and start over again (0->1.0->1.0->1.).

There is also a reverse flag that should be passed as the second argument:

rect.animate(3000).move(100, 100).loop(3, true)

Loops will then be completely reversed before starting over (0->1->0->1->0->1.).

returns: SVG.FX


Finally, you can add callback methods using after():

rect.animate(3000).move(100, 100).after(function() {
  this.animate().attr({ fill: '#f06' })

Note that the after() method will never be called if the animation is looping eternally.

returns: SVG.FX


Say you want to control the position of an animation with an external event, then the at() method will proove very useful:

var animation = draw.rect(100, 100).move(50, 50).animate('=').move(200, 200)

document.onmousemove = function(event) { / 1000)

In order to be able to use the at() method, the duration of the animation should be set to '='. The value passed as the first argument of at() should be a number between 0 and 1, 0 being the beginning of the animation and 1 being the end. Note that any values below 0 and above 1 will be normalized.

This functionality requires the fx.js module which is included in the default distribution.

returns: SVG.FX


The current situation of an animation is stored in the situation object:

rect.animate(3000).move(100, 100)
rect.fx.situation //-> everything is in here

Available values are:

Syntax sugar

Fill and stroke are used quite often. Therefore two convenience methods are provided:


The fill() method is a pretty alternative to the attr() method:

rect.fill({ color: '#f06', opacity: 0.6 })

A single hex string will work as well:


Last but not least, you can also use an image as fill, simply by passing an image url:


Or if you want more control over the size of the image, you can pass an image instance as well:

rect.fill(draw.image('images/shade.jpg', 20, 20))

returns: itself


The stroke() method is similar to fill():

rect.stroke({ color: '#f06', opacity: 0.6, width: 5 })

Like fill, a single hex string will work as well:


Not unlike the fill() method, you can also use an image as stroke, simply by passing an image url:


Or if you want more control over the size of the image, you can pass an image instance as well:

rect.stroke(draw.image('images/shade.jpg', 20, 20))

returns: itself


To set the overall opacity of an element:


returns: itself


The rotate() method will automatically rotate elements according to the center of the element:

// rotate(degrees)

Although you can also define a specific rotation point:

// rotate(degrees, cx, cy)
rect.rotate(45, 50, 50)

returns: itself


The skew() method will take an x and y value:

// skew(x, y)
rect.skew(0, 45)

returns: itself


The scale() method will take an x and y value:

// scale(x, y)
rect.scale(0.5, -1)

returns: itself


The translate() method will take an x and y value:

// translate(x, y)
rect.translate(0.5, -1)


Rects and ellipses have a radius() method. On rects it defines rounded corners, on ellipses the radii:


This will set the rx and ry attributes to 10. To set rx and ry individually:

rect.radius(10, 20)

This functionality requires the sugar.js module which is included in the default distribution.

returns: itself

Masking elements


The easiest way to mask is to use a single element:

var ellipse = draw.ellipse(80, 40).move(10, 10).fill({ color: '#fff' })


returns: itself


But you can also use multiple elements:

var ellipse = draw.ellipse(80, 40).move(10, 10).fill({ color: '#fff' })
var text = draw.text('SVG.JS').move(10, 10).font({ size: 36 }).fill({ color: '#fff' })

var mask = draw.mask().add(text).add(ellipse)


If you want the masked object to be rendered at 100% you need to set the fill color of the masking object to white. But you might also want to use a gradient:

var gradient = draw.gradient('linear', function(stop) {{ offset: 0, color: '#000' }){ offset: 1, color: '#fff' })

var ellipse = draw.ellipse(80, 40).move(10, 10).fill({ color: gradient })


returns: SVG.Mask


Unmasking the elements can be done with the unmask() method:


The unmask() method returns the masking element.

returns: itself


Removing the mask alltogether will also unmask() all masked elements as well:


returns: itself


For your convenience, the masking element is also referenced in the masked element. This can be useful in case you want to change the mask:


This functionality requires the mask.js module which is included in the default distribution.

Clipping elements

Clipping elements works exactly the same as masking elements. The only difference is that clipped elements will adopt the geometry of the clipping element. Therefore events are only triggered when entering the clipping element whereas with masks the masked element triggers the event. Another difference is that masks can define opacity with their fill color and clipPaths don't.


var ellipse = draw.ellipse(80, 40).move(10, 10)


returns: itself


Clip multiple elements:

var ellipse = draw.ellipse(80, 40).move(10, 10)
var text = draw.text('SVG.JS').move(10, 10).font({ size: 36 })

var clip = draw.clip().add(text).add(ellipse)


returns: SVG.ClipPath


Unclipping the elements can be done with the unclip() method:


returns: itself


Removing the clip alltogether will also unclip() all clipped elements as well:


returns: itself


For your convenience, the clipping element is also referenced in the clipped element. This can be useful in case you want to change the clipPath:

rect.clipper.move(10, 10)

This functionality requires the clip.js module which is included in the default distribution.

Arranging elements

You can arrange elements within their parent SVG document using the following methods.


Move element to the front:


returns: itself


Move element to the back:


returns: itself


Move element one step forward:


returns: itself


Move element one step backward:


returns: itself


The arrange.js module brings some additional methods. To get all siblings of rect, including rect itself:


returns: array


Get the position (a number) of rect between its siblings:


returns: number


Get the next sibling:

returns: element


Get the previous sibling:


returns: element


Insert an element before another:

// inserts circle before rect

returns: itself


Insert an element after another:

// inserts circle after rect

returns: itself

This functionality requires the arrange.js module which is included in the default distribution.


Sets are very useful if you want to modify or animate multiple elements at once. A set will accept all the same methods accessible on individual elements, even the ones that you add with your own plugins! Creating a set is exactly as you would expect:

// create some elements
var rect = draw.rect(100,100)
var circle =,100).fill('#f09')

// create a set and add the elements
var set = draw.set()

// change the fill of all elements in the set at once

A single element can be a member of many sets. Sets also don't have a structural representation, in fact they are just fancy array's.


Add an element to a set:


Quite a useful feature of sets is the ability to accept multiple elements at once:

set.add(rect, circle)

returns: itself


Iterating over all members in a set is the same as with svg containers:

set.each(function(i) {
  this.attr('id', 'shiny_new_id_' + i)

Note that this refers to the current child element.

returns: itself


Determine if an element is member of the set:


returns: boolean


Returns the index of a given element in the set.

set.index(rect) //-> -1 if element is not a member

returns: number


Gets the element at a given index:


returns: element


Gets the first element:


returns: element


Gets the last element:


returns: element


Get the bounding box of all elements in the set:


returns: SVG.BBox


To remove an element from a set:


returns: itself


Or to remove all elements from a set:


returns: itself


Sets work with animations as well:


returns: SVG.SetFX



There are linear and radial gradients. The linear gradient can be created like this:

var gradient = draw.gradient('linear', function(stop) {, '#333'), '#fff')

returns: SVG.Gradient


The offset and color parameters are required for stops, opacity is optional. Offset is float between 0 and 1, or a percentage value (e.g. 33%)., '#333')

or{ offset: 0, color: '#333', opacity: 1 })

returns: itself


To define the direction you can set from x, y and to x, y:

gradient.from(0, 0).to(0, 1)

The from and to values are also expressed in percent.

returns: itself


To define the direction you can set from x, y and to x, y:

gradient.from(0, 0).to(0, 1)

The from and to values are also expressed in percent.

returns: itself


Radial gradients have a radius() method to define the outermost radius to where the inner color should develop:

var gradient = draw.gradient('radial', function(stop) {, '#333'), '#fff')

gradient.from(0.5, 0.5).to(0.5, 0.5).radius(0.5)

returns: itself


A gradient can also be updated afterwards:

gradient.update(function(stop) {, '#333', 0.2), '#f03', 1)

And even a single stop can be updated:

var s1, s2, s3

draw.gradient('radial', function(stop) {
  s1 =, '#000')
  s2 =, '#f03')
  s3 =, '#066')

s1.update(0.1, '#0f0', 1)

returns: itself


The get() method makes it even easier to get a stop from an existing gradient:

var gradient = draw.gradient('radial', function(stop) {{ offset: 0, color: '#000', opacity: 1 })   // -> first{ offset: 0.5, color: '#f03', opacity: 1 }) // -> second{ offset: 1, color: '#066', opacity: 1 })   // -> third

var s1 = gradient.get(0) // -> returns "first" stop

returns: SVG.Stop


Finally, to use the gradient on an element:

rect.attr({ fill: gradient })



By passing the gradient instance as the fill on any element, the fill() method will be called:

gradient.fill() //-> returns 'url(#SvgjsGradient1234)'

W3Schools has a great example page on how
linear gradients and
radial gradients work.

This functionality requires the gradient.js module which is included in the default distribution.

returns: value



Creating a pattern is very similar to creating gradients:

var pattern = draw.pattern(20, 20, function(add) {

This creates a checkered pattern of 20 x 20 pixels. You can add any available element to your pattern.

returns: SVG.Pattern


A pattern can also be updated afterwards:

pattern.update(function(add) {,10)

returns: itself


Finally, to use the pattern on an element:

rect.attr({ fill: pattern })



By passing the pattern instance as the fill on any element, the fill() method will be called on th pattern instance:

pattern.fill() //-> returns 'url(#SvgjsPattern1234)'

returns: value



Markers can be added to every individual point of a line, polyline, polygon and path. There are three types of markers: start, mid and end. Where start represents the first point, end the last and mid every point in between.

var path = draw.path('M 100 200 C 200 100 300  0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100z')

path.fill('none').stroke({ width: 1 })

path.marker('start', 10, 10, function(add) {'#f06')
path.marker('mid', 10, 10, function(add) {
  add.rect(10, 10)
path.marker('end', 20, 20, function(add) {, 5), 15), 10)


The marker() method can be used in three ways. Firstly, a marker can be created on any container element (e.g. svg, nested, group, ...). This is useful if you plan to reuse the marker many times so it will create a marker in the defs but not show it yet:

var marker = draw.marker(10, 10, function(add) {
  add.rect(10, 10)

Secondly a marker can be created and applied directly on its target element:

path.marker('start', 10, 10, function(add) {'#f06')

This will create a marker in the defs and apply it directly. Note that the first argument defines the position of the marker and that there are four arguments as opposed to three with the first example.

Lastly, if a marker is created for reuse on a container element, it can be applied directly on the target element:

path.marker('mid', marker)

Finally, to get a marker instance from the target element reference:



By default the refX and refY attributes of a marker are set to respectively half the width nd height values. To define the refX and refY of a marker differently:

marker.ref(2, 7)

returns: itself


Updating the contents of a marker will clear() the existing content and add the content defined in the block passed as the first argument:

marker.update(function(add) {

returns: itself


Defines the markerWidth attribute:


returns: itself


Defines the markerHeight attribute:


returns: itself


Defines the markerWidth and markerHeight attributes:

marker.size(10, 10)

returns: itself



The data() method allows you to bind arbitrary objects, strings and numbers to SVG elements:'key', { value: { data: 0.3 }})

Or set multiple values at once:{
  forbidden: 'fruit'
, multiple: {
    values: 'in'
  , an: 'object'

returns: itself


Fetching the values is similar to the attr() method:'key')

returns: itself


Removing the data altogether:'key', null)

returns: itself

Sustaining data types

Your values will always be stored as JSON and in some cases this might not be desirable. If you want to store the value as-is, just pass true as the third argument:'key', 'value', true)

returns: itself



Storing data in-memory is very much like setting attributes:

rect.remember('oldBBox', rect.bbox())

Multiple values can also be remembered at once:

  oldFill:    rect.attr('fill')
, oldStroke:  rect.attr('stroke')

To retrieve a memory


returns: itself


Erasing a single memory:


Or erasing multiple memories at once:

rect.forget('oldFill', 'oldStroke')

And finally, just erasing the whole memory:


returns: itself


Basic events

Events can be bound to elements as follows: {
  this.fill({ color: '#f06' })

Removing it is quite as easy:

All available events are: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, touchstart, touchmove, touchleave, touchend and touchcancel.

returns: itself

Event listeners

You can also bind event listeners to elements:

var click = function() {
  this.fill({ color: '#f06' })

rect.on('click', click)

returns: itself

Unbinding events is just as easy:'click', click)

Or to unbind all listeners for a given event:'click')

Or even unbind all listeners for all events:

returns: itself

But there is more to event listeners. You can bind events to html elements as well:

SVG.on(window, 'click', click)

Obviously unbinding is practically the same:, 'click', click)

Custom events

You can even use your own events.

Just add an event listener for your event:

rect.on('myevent', function() {

Now you are ready to fire the event whenever you need:

function whenSomethingHappens() {'myevent') 

You can also pass some data to the event:

function whenSomethingHappens() {'myevent', {some:'data'}) 

rect.on('myevent', function(e) {
  alert(e.detail.some) // outputs 'data'

svg.js supports namespaced events following the syntax event.namespace.

A namespaced event behaves like a normal event with the difference that you can remove it without touching handlers from other namespaces.

// attach
rect.on('myevent.namespace', function(e) {
  // do something

// detach all handlers of namespace'myevent.namespace')

// detach all handlers including all namespaces'myevent)

However you can't fire a specific namespaced event. Calling'myevent.namespace') won't do anything while'myevent') works and fires all attached handlers of the event

Important: always make sure you namespace your event to avoid conflicts. Preferably use something very specific. So event.wicked for example would be better than something generic like event.svg.


Numbers in SVG.js have a dedicated number class to be able to process string values. Creating a new number is simple:

var number = new SVG.Number('78%')'3%').toString() //-> returns '81%'
number.valueOf() //-> returns 0.81

Operators are defined as methods on the SVG.Number instance.



returns: SVG.Number




returns: SVG.Number




returns: SVG.Number




returns: SVG.Number


Change number to another unit:'px')

returns: SVG.Number


Make a number morphable:


returns: itself


Get morphable number at given position:

var number = new SVG.Number('79%').morph('3%') //-> '37.2%'

returns: SVG.Number


Svg.js has a dedicated color class handling different types of colors. Accepted values are:

Note that when working with objects is important to provide all three values every time.

The SVG.Color instance has a few methods of its own.


Get hex value:

color.toHex() //-> returns '#ff0066'

returns: hex color string


Get rgb string value:

color.toRgb() //-> returns 'rgb(255,0,102)'

returns: rgb color string


Get the brightness of a color:

color.brightness() //-> returns 0.344

This is the perceived brighness where 0 is black and 1 is white.

returns: number


Make a color morphable:


returns: itself


Get morphable color at given position:

var color = new SVG.Color('#ff0066').morph('#000') //-> '#7f0033'

returns: SVG.Color


In SVG.js every value list string can be cast and passed as an array. This makes writing them more convenient but also adds a lot of key functionality to them.


Is for simple, whitespace separated value strings:

'0.343 0.669 0.119 0 0 0.249 -0.626 0.13 0 0 0.172 0.334 0.111 0 0 0 0 0 1 0'

Can also be passed like this in a more manageable format:

new SVG.Array([ .343,  .669, .119, 0,   0 
              , .249, -.626, .130, 0,   0
              , .172,  .334, .111, 0,   0
              , .000,  .000, .000, 1,  -0 ])


Is a bit more complex and is used for polyline and polygon elements. This is a poly-point string:

'0,0 100,100'

The dynamic representation:

  [0, 0]
, [100, 100]

Precompiling it as an SVG.PointArray:

new SVG.PointArray([
  [0, 0]
, [100, 100]

Note that every instance of SVG.Polyline and SVG.Polygon carries a reference to the SVG.PointArray instance:

polygon.array() //-> returns the SVG.PointArray instance

Javascript inheritance stack: SVG.PointArray < SVG.Array


Path arrays carry arrays representing every segment in a path string:

'M0 0L100 100z'

The dynamic representation:

  ['M', 0, 0]
, ['L', 100, 100]
, ['z']

Precompiling it as an SVG.PathArray:

new SVG.PathArray([
  ['M', 0, 0]
, ['L', 100, 100]
, ['z']

Note that every instance of SVG.Path carries a reference to the SVG.PathArray instance:

path.array() //-> returns the SVG.PathArray instance


The syntax for patharrays is very predictable. They are basically literal representations in the form of two dimentional arrays.

Move To

Original syntax is M0 0 or m0 0. The SVG.js syntax ['M',0,0] or ['m',0,0].

Line To

Original syntax is L100 100 or l100 100. The SVG.js syntax ['L',100,100] or ['l',100,100].

Horizontal line

Original syntax is H200 or h200. The SVG.js syntax ['H',200] or ['h',200].

Vertical line

Original syntax is V300 or v300. The SVG.js syntax ['V',300] or ['v',300].

Bezier curve

Original syntax is C20 20 40 20 50 10 or c20 20 40 20 50 10. The SVG.js syntax ['C',20,20,40,20,50,10] or ['c',20,20,40,20,50,10].

Or mirrored with S:

Original syntax is S40 20 50 10 or s40 20 50 10. The SVG.js syntax ['S',40,20,50,10] or ['s',40,20,50,10].

Or quadratic with Q:

Original syntax is Q20 20 50 10 or q20 20 50 10. The SVG.js syntax ['Q',20,20,50,10] or ['q',20,20,50,10].

Or a complete shortcut with T:

Original syntax is T50 10 or t50 10. The SVG.js syntax ['T',50,10] or ['t',50,10].


Original syntax is A 30 50 0 0 1 162 163 or a 30 50 0 0 1 162 163. The SVG.js syntax ['A',30,50,0,0,1,162,163] or ['a',30,50,0,0,1,162,163].


Original syntax is Z or z. The SVG.js syntax ['Z'] or ['z'].

The best documentation on paths can be found at

Javascript inheritance stack: SVG.PathArray < SVG.Array


In order to animate array values the morph() method lets you pass a destination value. This can be either the string value, a plain array or an instance of the same type of SVG.js array:

var array = new SVG.PointArray([[0, 0], [100, 100]])
array.morph('100,0 0,100 200,200')

This method will prepare the array ensuring both the source and destination arrays have the same length.

Note that this method is currently not available on SVG.PathArray but will be soon.

returns: itself


This method will morph the array to a given position between 0 and 1. Continuing with the previous example: //-> returns '27,0 73,100 127,127'

Note that this method is currently not available on SVG.PathArray but will be soon.

returns: new instance


When morphing is done the settle() method will eliminate any transitional points like duplicates:


Note that this method is currently not available on SVG.PathArray but will be soon.

returns: itself


Moves geometry of the array with the given x and y values:

var array = new SVG.PointArray([[0, 0], [100, 100]])
array.toString() //-> returns '33,75 133,175'

Note that this method is only available on SVG.PointArray and SVG.PathArray

returns: itself


Resizes geometry of the array by the given width and height values:

var array = new SVG.PointArray([[0, 0], [100, 100]])
array.toString() //-> returns '100,100 322,433'

Note that this method is only available on SVG.PointArray and SVG.PathArray

returns: itself


Reverses the order of the array:

var array = new SVG.PointArray([[0, 0], [100, 100]])
array.toString() //-> returns '100,100 0,0'

returns: itself


Gets the bounding box of the geometry of the array:


Note that this method is only available on SVG.PointArray and SVG.PathArray

returns: object


Matrices in SVG.js have their own class SVG.Matrix, wrapping the native SVGMatrix. They add a lot of functionality like extracting transform values, matrix morphing and improvements on the native methods.


In SVG.js matrices accept various values on initialization.

Without a value:

var matrix = new SVG.Matrix
matrix.toString() //-> returns matrix(1,0,0,1,0,0)

Six arguments:

var matrix = new SVG.Matrix(1, 0, 0, 1, 100, 150)
matrix.toString() //-> returns matrix(1,0,0,1,100,150)

A string value:

var matrix = new SVG.Matrix('1,0,0,1,100,150')
matrix.toString() //-> returns matrix(1,0,0,1,100,150)

An object value:

var matrix = new SVG.Matrix({ a: 1, b: 0, c: 0, d: 1, e: 100, f: 150 })
matrix.toString() //-> returns matrix(1,0,0,1,100,150)

A native SVGMatrix:

var svgMatrix = svgElement.getCTM()
var matrix = new SVG.Matrix(svgMatrix)
matrix.toString() //-> returns matrix(1,0,0,1,0,0)

Even an instance of SVG.Element:

var rect = draw.rect(50, 25)
var matrix = new SVG.Matrix(rect)
matrix.toString() //-> returns matrix(1,0,0,1,0,0)


Gets the calculated values of the matrix as an object:


The returned object contains the following values:

returns: object


Returns an exact copy of the matrix:


returns: SVG.Matrix


In order to animate matrices the morph() method lets you pass a destination matrix. This can be any value a SVG.Matrix would accept on initialization:


returns: itself


This method will morph the matrix to a given position between 0 and 1:

This will only work when a destination matirx is defined using the morph() method.

returns: SVG.Matrix


Multiplies by another given matrix:


returns: SVG.Matrix


Creates an inverted matix:


returns: SVG.Matrix


Translates matrix by a given x and y value:

matrix.translate(10, 20)

returns: SVG.Matrix


Scales matrix uniformal with one value:

// scale

Scales matrix non-uniformal with two values:

// scaleX, scaleY
matrix.scale(2, 3)

Scales matrix uniformal on a given center point with three values:

// scale, cx, cy
matrix.scale(2, 100, 150)

Scales matrix non-uniformal on a given center point with four values:

// scaleX, scaleY, cx, cy
matrix.scale(2, 3, 100, 150)

returns: SVG.Matrix


Rotates matrix by degrees with one value given:

// degrees

Rotates a matrix by degrees around a given point with three values:

// degrees, cx, cy
matrix.rotate(45, 100, 150)

returns: SVG.Matrix


Flips matrix over a given axis:




By default elements are flipped over their center point. The flip axis position can be defined with the second argument:

matrix.flip('x', 150)


matrix.flip('y', 100)

returns: SVG.Matrix


Skews matrix a given degrees over x and or y axis with two values:

// degreesX, degreesY
matrix.skew(0, 45)

Skews matrix a given degrees over x and or y axis on a given point with four values:

// degreesX, degreesY, cx, cy
matrix.skew(0, 45, 150, 100)

returns: SVG.Matrix


Performs a given matrix transformation around a given center point:

// cx, cy, matrix
matrix.around(100, 150, new SVG.Matrix().skew(0, 45))

The matrix passed as the third argument will be used to multiply.

returns: SVG.Matrix


Returns a native SVGMatrix extracted from the SVG.Matrix instance:


returns: SVGMatrix


Converts the matrix to a transform string:

// -> matrix(1,0,0,1,0,0)

returns: string

Extending functionality


Creating your own custom elements with SVG.js is a piece of cake thanks to the SVG.invent function. For the sake of this example, lets "invent" a shape. We want a rect with rounded corners that are always proportional to the height of the element. The new shape lives in the SVG namespace and is called Rounded. Here is how we achieve that.

SVG.Rounded = SVG.invent({
  // Define the type of element that should be created
  create: 'rect'

  // Specify from which existing class this shape inherits
, inherit: SVG.Shape

  // Add custom methods to invented shape
, extend: {
    // Create method to proportionally scale the rounded corners
    size: function(width, height) {
      return this.attr({
        width:  width
      , height: height
      , rx:     height / 5
      , ry:     height / 5

  // Add method to parent elements
, construct: {
    // Create a rounded element
    rounded: function(width, height) {
      return this.put(new SVG.Rounded).size(width, height)


To create the element in your drawing:

var rounded = draw.rounded(200, 100)

That's it, the invention is now ready to be used!

Accepted values

The SVG.invent() function always expects an object. The object can have the following configuration values:

Svg.js uses the SVG.invent() function to create all internal elements, so have a look at the source to see how this function is used in various ways.


SVG.js has a modular structure. It is very easy to add you own methods at different levels. Let's say we want to add a method to all shape types then we would add our method to SVG.Shape:

SVG.extend(SVG.Shape, {
  paintRed: function() {
    return this.fill('red')

Now all shapes will have the paintRed method available. Say we want to have the paintRed method on an ellipse apply a slightly different color:

SVG.extend(SVG.Ellipse, {
  paintRed: function() {
    return this.fill('orangered')

The complete inheritance stack for SVG.Ellipse is:

SVG.Ellipse < SVG.Shape < SVG.Element

The SVG document can be extended by using:

SVG.extend(SVG.Doc, {
  paintAllPink: function() {
    this.each(function() {

You can also extend multiple elements at once:

SVG.extend(SVG.Ellipse, SVG.Path, SVG.Polygon, {
  paintRed: function() {
    return this.fill('orangered')


Here are a few nice plugins that are available for SVG.js:

** Caution: Not tested for SVG.js 2.0 **


svg.absorb.js absorb raw SVG data into an SVG.js instance.


svg.draggable.js to make elements draggable.


svg.connectable.js to connect elements.

svg.connectable.js fork to connect elements (added: curved connectors, you can use any self-made path as a connector, choosable 'center'/'perifery' attachment, 'perifery' attachment for source / target SVG Paths uses smallest-distance algorithm between PathArray points)


svg.easing.js for more easing methods on animations.


svg.export.js export raw SVG.


svg.filter.js adding svg filters to elements.


svg.foreignobject.js foreignObject implementation (by john-memloom).


svg.import.js import raw SVG data.


svg.math.js a math extension (by Nils Lagerkvist).


svg.path.js for manually drawing paths (by Nils Lagerkvist).


svg.shapes.js for more polygon based shapes.


svg.topath.js to convert any other shape to a path.


svg.topoly.js to convert a path to polygon or polyline.


svg.wiml.js a templating language for svg output.


comic.js to cartoonize any given svg.


svg.draw.js to draw elements with your mouse

select to select elements


svg.resize.js to resize elements with your mouse


We love contributions. Yes indeed, we used the word LOVE! But please make sure you follow the same coding style. Here are some guidelines.


We do it with two spaces. Make sure you don't start using tabs because then things get messy.

Avoid hairy code

We like to keep things simple and clean, don't write anything you don't need. So use single quotes where possible and avoid semicolons, we're not writing PHP here.


var text = draw.text('with single quotes here')
  , nest = draw.nested().attr('x', '50%')

for (var i = 0; i < 5; i++)
  if (i != 3) * 100)


var text = draw.text("with single quotes here");
var nest = draw.nested().attr("x", "50%");

for (var i = 0; i < 5; i++) {
  if (i != 3) {;

Minimize variable declarations

All local variables should be declared at the beginning of a function or method unless there is ony one variable to declare. Although it is not required to assign them at the same moment. When if statements are involved, requiring some variables only to be present in the statement, the necessary variables should be declared right after the if statement.


function reading_board() {
  var aap, noot, mies

  aap  = 1
  noot = 2
  mies = aap + noot


function reading_board() {
  var aap  = 1
  var noot = 2
  var mies = aap + noot

Let your code breathe people!

Don't try to be a code compressor yourself, they do way a better job anyway. Give your code some spaces and newlines.


var nest = draw.nested().attr({
  x:      10
, y:      20
, width:  200
, height: 300

for (var i = 0; i < 5; i++)


var nest=draw.nested().attr({x:10,y:20,width:200,height:300});
for(var i=0;i<5;i++);

It won't hurt to add a few comments

Where necessary tell us what you are doing but be concise. We only use single-line comments. Also keep your variable and method names short while maintaining readability.


// Adds orange-specific methods
SVG.extend(SVG.Rect, {
  // Add a nice, transparent orange
  orangify: function() {
    // fill with orange color

    // add a slight opacity
    return this.opacity(0.85)


 * does something with orange and opacity
SVG.extend(SVG.Rect, {
  orgf: function() {
    return this.fill('orange').opacity(0.85)

Refactor your code

Once your implementation is ready, revisit and rework it. We like to keep it DRY.

Test. Your. Code.

It's not that hard to write at least one example per implementation, although we prefer more. Your code might seem to work by quickly testing it in your brwoser but more than often you can't forsee everything.

Before running the specs you will need to build the library. Be aware that pull requests without specs will be declined.


After contributing you probably want to build the library to run some specs. Make sure you have Node.js installed on your system, cd to the svg.js directory and run:

$ npm install

Build SVG.js by running gulp:

$ gulp

The resulting files are:

  1. dist/svg.js
  2. dist/svg.min.js




Visit the SVG.js test page if you want to check compatibility with different browsers.

Acknowledgements & Thanks

Documentation kindly provided by DocumentUp

SVG.js and its documentation is released under the terms of the MIT license.