SVG.js

Attributes

attr() as setter

returns itself
animate yes (only for numbers, arrays, colors, ...)

Set a single attribute:

rect.attr('x', 50)

Set multiple attributes at once:

rect.attr({
  fill: '#f06'
, 'fill-opacity': 0.5
, stroke: '#000'
, 'stroke-width': 10
})

Set an attribute with a namespace:

rect.attr('x', 50, 'http://www.w3.org/2000/svg')

Explicitly remove an attribute:

rect.attr('fill', null)

attr() as getter

returns value (string, number, ...)

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

Get a single attribute:

var x = rect.attr('x')

Get all attributes as an object:

var attributes = rect.attr()

Get only specified attributes:

var attributes = rect.attr(['x', 'y'])


Positioning

While positioning an element by directly setting its attributes works only if the attributes are used natively by that type of element, the positioning methods described below are much more convenient as they work for all element types.

For example, the following code works because each element is positioned by setting native attributes:

rect.attr({ x: 20, y: 60 })
circle.attr({ cx: 50, cy: 40 })

The rect will be moved by its upper left corner to the new coordinates, and the circle will be moved by its centre. However, trying to move a circle by its 'corner' or a rect by its centre in this way will fail. The following lines will get silently ignored as the attributes that are addressed are not natively used by the element setting them:

rect.attr({ cx: 20, cy: 60 })
circle.attr({ x: 50, y: 40 })

However, the positioning methods detailed below will work for all element types, regardless of whether the attributes being addressed are native to the type. So, unlike the lines above, these lines work just fine:

rect.cx(20).cy(60)
circle.x(50).y(40)

It is important to note, though, that these methods are only intended for use with user (unitless) coordinates. If for example, an element has its size set via percentages or other units, the positioning methods that address its native attributes will most likely still work, but the ones that address non-native attributes will give unexpected results -- as both getters and setters!

move()

returns itself
animate yes

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

rect.move(200, 350)

x() as setter

returns itself
animate yes

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

rect.x(200)

x() as getter

returns value

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

var x = rect.x()

y() as setter

returns itself
animate yes

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

rect.y(350)

y() as getter

returns value

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

var y = rect.y()

center()

returns itself
animate yes

Move the element by its center to a given cx and cy position:

rect.center(150, 150)

cx() as setter

returns itself
animate yes

Move the element by its centre in the x direction only:

rect.cx(200)

cx() as getter

returns value

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

var cx = rect.cx()

cy() as setter

returns itself
animate yes

Move the element by its centre in the y direction only:

rect.cy(350)

cy() as getter

returns value

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

var cy = rect.cy()

dmove()

returns itself
animate yes

Shift the element in both the x and y directions relative to its current position:

rect.dmove(10, 30)

Note: when using dmove() (and dx() or dy() too for that matter), always make sure you provide values of the same unit the element is originally positioned in. So if the element is at x:10%, use element.dx('5%') and not element.dx('5px').

dx()

returns itself
animate yes

Shift the element in the x direction relative to its current position:

rect.dx(200)

dy()

returns itself
animate yes

Shift the element in the y direction relative to its current position:

rect.dy(200)


Resizing

size()

returns itself
animate yes

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

rect.size(200, 300)

Proportional resizing is also possible by leaving out height:

rect.size(200)

Or by passing null as the value for width:

rect.size(null, 200)

As with positioning, 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.

width() as setter

returns itself
animate yes

Set the width of an element:

rect.width(200)

width() as getter

returns value

var width = rect.width()

height() as setter

returns itself
animate yes

Set the height of an element:

rect.height(325)

height() as getter

returns value

rect.height()

radius()

returns itself
animate yes

Circles, ellipses, and rects may use the radius() method. On rects, it defines rounded corners.

For a circle, the argument sets the r attribute.

circle.radius(10)

For ellipses and rects, pass two arguments to set the rx and ry attributes individually. Or, pass a single argument, to make the two attributes equal.

ellipse.radius(10, 20)
rect.radius(5)


Syntactic sugar

fill()

returns itself

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:

rect.fill('#f06')

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

rect.fill('images/shade.jpg')

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

rect.fill(draw.image('images/shade.jpg', function() {
  this.size(20, 20)
}))

stroke()

returns itself

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

rect.stroke({
  color: '#f06',
  opacity: 0.6,
  width: 5,
  linecap: 'round',
  linejoin: 'round',
  miterlimit: 4,
  dasharray: '10,5',
  dashoffset: 2
})

The object keys map to SVG stroke attributes. For example, linecap sets
stroke-linecap and dasharray sets stroke-dasharray.

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

rect.stroke('#f06')

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

rect.stroke('images/shade.jpg')

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))

opacity()

returns itself

To set the overall opacity of an element:

rect.opacity(0.5)


Transforming

SVG transforms change an element's coordinate system without rewriting its
geometry. SVG.js stores the result in the element's transform attribute as a
matrix. The examples below use local element coordinates; transforms inherited
from parent elements are not included unless stated otherwise.

transform() as setter

returns itself
animate yes

With one argument, transform() replaces the element's current local transform
with the requested transform:

element.transform({
  rotate: 125,
  translateX: 50,
  translateY: 100,
  scale: 3
})

The transform object accepts the following values and aliases:

Transform Accepted forms
Translation translate: [x, y], translate: {x, y}, translateX, translateY, tx, ty
Rotation rotate: degrees or theta: degrees
Scale scale: factor, scale: [x, y], scaleX, scaleY
Skew skew: degrees, skew: [x, y], skewX, skewY
Shear shear: factor
Flip flip: 'x', flip: 'y', flip: 'both', or flip: true
Origin origin: [x, y], origin: {x, y}, originX, originY, ox, oy
Final origin position position: [x, y], position: {x, y}, positionX, positionY, px, py
Relative origin movement relative: [x, y], relative: {x, y}, relativeX, relativeY, rx, ry

The origin defaults to the center of the element's bounding box. It can also be
given with one or two of center, top, bottom, left, and right:

element.transform({
  translate: [10, 20],
  origin: 'top left',
  flip: 'both'
})

position moves the transformed origin to the supplied coordinates, while
relative moves it by the supplied amount.

You can also pass an SVG.Matrix or an object with a through f matrix
components:

element.transform({
  a: 1, b: 0, c: 0, d: 1, e: 10, f: 20
})

Absolute and relative transforms

The default is absolute: each call replaces the element's existing local
transform. Pass true as the second argument to compose the new transform with
the current one instead:

element.transform({ rotate: 125 })
element.transform({ rotate: 37.5 }, true) // adds another rotation

The transform sugar methods such as translate(), rotate(), and scale() are
relative: repeated calls compose instead of replacing the previous transform.

An element or matrix can be supplied instead of true to use its local matrix
as the base:

element.transform({ rotate: 125 }, someElement)
element.transform({ rotate: 125 }, someMatrix)

transform() as getter

returns value

Without an argument, transform() decomposes the element's current local matrix:

element.transform()

The returned object contains:

  • translateX and translateY (calculated translation)
  • shear (calculated x-axis shear)
  • scaleX and scaleY (calculated scale)
  • rotate (calculated rotation in degrees)
  • originX and originY (both 0 for this getter)
  • a, b, c, d, e, and f (the matrix components)

These values are a decomposition of the resulting matrix, not a record of the
individual transform calls that produced it. Equivalent transform chains can
therefore return the same values. Pass a property name to retrieve just one
value:

element.transform('rotate')

Parent transforms are not included. Use ctm() or screenCTM() when you need
an accumulated coordinate-system matrix.

matrix()

returns itself as a setter, SVG.Matrix as a getter
animate yes

matrix() writes a matrix directly to the transform attribute. Pass an
SVG.Matrix or six matrix components:

element.matrix(new SVG.Matrix().translate(20, 30))
element.matrix(1, 0, 0, 1, 20, 30)

const matrix = element.matrix()

Unlike transform({...}, true), the setter does not compose with the current
transform; it replaces it.

matrixify()

returns SVG.Matrix

Combines the transformations in the element's own transform attribute into one matrix. Parent transformations are not included and the element is not changed:

element.attr('transform', 'translate(20 30) rotate(45)')

const localMatrix = element.matrixify()

Use ctm() or screenCTM() when you need transformations inherited from ancestors.

ctm()

returns SVG.Matrix

Returns the element's current transformation matrix in its SVG viewport coordinate system. This wraps the browser's native getCTM() result in SVG.Matrix:

const matrix = element.ctm()
const pointInViewport = new SVG.Point(0, 0).transform(matrix)

screenCTM()

returns SVG.Matrix

Returns the matrix from the element's local coordinates to screen coordinates. This includes transformations from SVG ancestors:

const screenMatrix = element.screenCTM()
const screenPoint = new SVG.Point(0, 0).transform(screenMatrix)

For the inverse conversion, use screenCTM().inverse() or the element's point() helper:

const localPoint = element.point(event.clientX, event.clientY)

The element must be rendered for the browser to provide a meaningful screen matrix. If the browser cannot calculate one, SVG.js logs a warning and returns an identity matrix.

untransform()

returns itself

Removes the element's transform attribute:

element.untransform()

This does not rewrite the element's geometry to preserve its visual position. Use toParent() when moving an element between parents without changing its visual appearance.

flip()

returns itself
animate yes

Flips an element over the x-axis, y-axis, or both axes:

element.flip('x')
element.flip('y')

By default, elements are flipped around their center. The flip origin can be
defined with the second argument:

element.flip('x', { x: 20, y: 30 })

Omit the axis, or pass 'both' or true, to flip both axes:

element.flip()
element.flip('both')
element.flip(true)

rotate()

returns itself
animate yes

rotate() uses the center of the element by default:

element.rotate(45)

Pass a specific rotation origin when needed:

element.rotate(45, 50, 50)

skew()

returns itself
animate yes

skew() takes x-axis and y-axis angles. Pass an origin as the third and fourth
arguments when needed:

element.skew(0, 45)
element.skew(10, 20, 50, 50)

shear()

returns itself
animate yes

Applies an x-axis shear factor, optionally around an origin:

element.shear(0.5)
element.shear(0.5, 50, 50)

scale()

returns itself
animate yes

scale() accepts one factor for uniform scaling or separate x and y factors:

element.scale(2)
element.scale(0.5, -1)

By default, scaling uses the center of the element. Pass an origin after the
scale factors when needed:

element.scale(2, 0, 0)
element.scale(0.5, -1, 0, 0)

translate()

returns itself
animate yes

Applies a relative x and y translation:

element.translate(0.5, -1)

relative()

returns itself
animate yes

Moves the transformed origin by a relative x and y amount. This is the helper
form of transform({ relative: [x, y] }, true):

element.relative(20, 10)


Styles

css() as setter

returns itself

With the css() method the style attribute can be managed like attributes with attr:

element.css('cursor', 'pointer')

Multiple styles can be set at once using an object:

element.css({ cursor: 'pointer', fill: '#f03' })

Explicitly deleting individual style definitions works the same as with the attr() method:

element.css('cursor', null)

css() as getter

returns value (string, number, ...)

Similar to attr() the css() method can also act as a getter:

element.css('cursor')
// => pointer

Or even a full getter:

element.css()
// => {cursor:pointer;fill:#f03;}

You can also get only specific styles by using an array:

element.css(['cursor', 'fill'])
// => {cursor:pointer;fill:#f03;}

hide()

returns itself

Hide element:

element.hide()

show()

returns itself

Show (unhide) element:

element.show()

visible()

returns boolean

To check if the element is visible:

element.visible()


Id Attribute

The id() method allows you to get, and set, the id attribute of SVG elements.

id() as getter

returns id

Gets the id attribute, creating a new unique id if one is not already set:

var id = rect.id()

id() as setter

returns id

Sets the id attribute:

rect.id('my-unique-id')

Removing the id altogether:

rect.id(null)


Class Names

addClass()

returns itself

Adds a given css class:

element.addClass('pink-flower')

classes()

returns array

Fetches the CSS classes for the node as an array:

element.classes()

hasClass()

returns boolean

Test the presence of a given css class:

element.hasClass('purple-rain')

removeClass()

returns itself

Removes a given css class:

element.removeClass('pink-flower')

toggleClass()

returns itself

Toggles a given css class:

element.toggleClass('pink-flower')


Data

The data() method allows you to bind arbitrary objects, strings and numbers to SVG elements.

data() as getter

returns value

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

var obj = rect.data()
var value = rect.data('key')
var obj2 = rect.data(['key1', 'key2'])

data() as setter

returns itself

rect.data('key', { value: { data: 0.3 }})

Or set multiple values at once:

rect.data({
  forbidden: 'fruit'
, multiple: {
    values: 'in'
  , an: 'object'
  }
})

Removing the data altogether:

rect.data('key', null)

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:

rect.data('key', 'value', true)


Memory

remember() as getter

returns value

To retrieve a memory

rect.remember('oldBBox')

remember() as setter

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:

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

forget()

returns itself

Erasing a single memory:

rect.forget('oldBBox')

Or erasing multiple memories at once:

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

And finally, just erasing the whole memory:

rect.forget()


Document Tree

add()

returns itself

Sets the calling element as the parent node of the argument. Returns the parent:

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

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

You can also pass a css selector, a node or an svg string:

group.add('#someEl')
group.add(document.getElementById('someEl'))
group.add('<rect>')

add() also accepts a second argument specifying at which position the element will be inserted:

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

group.circle(100, 100)
group.add(rect, 0) //-> inserts rect as first child

addTo()

returns itself

Sets the calling element as a child node of the argument. Returns the child:

rect.addTo(group) //-> returns rect
rect.addTo('#someEl')
rect.addTo(document.body)
rect.addTo('<g>')

addTo() accepts a second argument specifying the position (see add())

clone()

returns SVG.Element

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

var clone = rect.clone()

By default clone() will make a deep clone (it also clones the children) and assigns new ids to every elements. You can change that behavior by passing 2 arguments:

var makeDeepClone = false
var assignNewId = false
var clone = rect.clone(makeDeepClone, assignNewId)

clone() will create a new, unlinked element. For making a linked clone, see the use element.
To insert the clone, use addTo() or add().

put()

returns SVG.Element

Sets the calling element as the parent node of the argument. Returns the child. In case the child wasn't an svgjs object, an svgjs object is created and returned:

group.put(rect) //-> returns rect
group.put('#myRect') //-> returns SVG.Rect with id myRect
group.put(document.getElementById('myRect')) //-> returns SVG.Rect with id myRect
group.put('<rect>') //-> returns SVG.Rect

put() accepts a second argument specifying the position (see add())

putIn()

returns SVG.Element

Sets the calling element as a child node of the argument. Returns the parent. In case the parent wasn't an svgjs object, an svgjs object is created and returned:

rect.putIn(group) //-> returns group
rect.putIn('#myGroup') //-> returns SVG.G with id myGroup
group.put(document.getElementById('myGroup')) //-> returns SVG.G with id myGroup
rect.putIn('<g>') //-> returns SVG.G

putIn() accepts a second argument specifying the position (see add())

remove()

returns itself

Removes the calling element from the svg document:

rect.remove()

replace()

returns SVG.Element

At the calling element's position in the svg document, replace the calling element with the element passed to the method.

rect.replace(draw.circle(100))

toRoot()

returns itself

Same as toParent() but with the root-node as parent. toRoot() takes a position as parameter and appends by default.

toParent()

returns itself

Moves an element to a different parent (similar to addTo), but without changing its visual representation. All transformations are merged and applied to the element.

rect.toParent(group) // looks the same as before

You can specifiy the position at which the element is inserted by passing a second parameter:

rect.toParent(group, 3) // inserted at position 3 (4th child)

ungroup()

returns itself

Breaks up a groupd and puts all of its elements into the parent of the group without changing their visual representation. That means, any transformation applied to the group is now applied to its individual elements.

group.rect(100, 200)
group.circle(4)
group.transform({rotate: 20}).ungroup()
// group is deleted, rect and circle both have rotate: 20

You can also specify to which container the elements of the group are moved and at which position they are inserted:

group.ungroup(otherContainer, position)

Note: Defs elements can not be ungrouped

flatten()

returns itself

Breaks up all containers contained in an element and flattens the svg structure so that all elements end up in the element flatten() was called on.

Call it on the root node to get a flat svg structure:

drawing.flatten()

Flatten and export svg:

var svgString = drawing.flatten().svg()

To put all elements into another comtainer and remove the current element, you can call ungroup() right after flatten:

var svgString = drawing.flatten().ungroup(otherContainer)

Note: Defs elements can not be flattened

wrap()

returns itself

Wraps the passed element around the current element. This replaces the current element with the wrapping element and appends the current element to the wrapped element.

rect.wrap('<g>')
rect.wrap(new G())


Arranging

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

after()

returns itself

Insert an element after another:

// inserts circle after rect
rect.after(circle)

before()

returns itself

Insert an element before another:

// inserts circle before rect
rect.before(circle)

insertAfter()

returns itself

Insert the current element behind the passed element

rect.insertAfter(circle)

insertBefore()

returns itself

Insert the current element before the passed element

rect.insertBefore(circle)

back()

returns itself

Move element to the back:

rect.back()

backward()

returns itself

Move element one step backward:

rect.backward()

front()

returns itself

Move element to the front:

rect.front()

forward()

returns itself

Move element one step forward:

rect.forward()

next()

returns SVG.Element

Get the next sibling:

rect.next()

position()

returns number

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

rect.position()

prev()

returns SVG.Element

Get the previous sibling:

rect.prev()

siblings()

returns array

To get all siblings of rect, including rect itself:

rect.siblings()


Geometry

point()

returns SVG.Point

Transforms a point from screen coordinates to the elements coordinate system.

// e is some mouseevent
var point = path.point(e.pageX, e.pageY) // {x, y}

inside()

returns boolean

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.

bbox()

returns SVG.Box

Gives the bounding box of an element which is the untransformed tightest box around the element.

element.bbox()

rbox()

returns SVG.Box

Returns the transformed box of an element which is the transformed tightest box around the element. To specify to which coordinate system the box is transformed, relatively it is possible to pass in an element:

element.rbox(drawing)
// transformed box in coordinates of drawing

This method is a convenient wrapper around getBoundingClientRect().

viewbox()

viewbox() as setter

Sets the viewbox of an element (only available on elements which support viewbox)

drawing.viewbox(10, 10, 500, 600)
// or
drawing.viewbox('10 10 500 600')
// or
drawing.viewbox(box)

viewbox() as getter

returns SVG.Box

drawing.viewbox()

zoom()

zoom() as setter

Sets the zoom of an element (only available on elements which support viewbox).
Make sure, to also set an absolute width and height for best results.

// zooms to level 10
drawing.zoom(10)

// zooms into the point {x: 20, y: 20}
drawing.zoom(10, {x: 20, y: 20})

zoom() as getter

returns number

drawing.zoom()

For wheel and pinch zoom support, have a look at svg.panzoom.js

Fork me on GitHub