SVG Reference

This Javascript library helps you easily craft SVG images. The web editor has some examples to get you started (roll the dice). Download the library here.

Sections

  1. Shapes
  2. Overview
  3. Appendix

Shapes

SVG()
line(x1, y1, x2, y2)
circle(x, y, radius)
ellipse(x, y, rx, ry)
rect(x, y, width, height)
polygon(pointsArray)
polyline(pointsArray)
path()
text(textString, x, y)

Layers and Masks

g()
clipPath()
mask()

Outside the Specification

regularPolygon(sides, cX, cY, radius)
parabola(x, y, width, height)
curve(x1, y1, x2, y2, bend)
arc(x, y, radius, angleA, angleB)
wedge(x, y, radius, angleA, angleB)

Events

onMove, onPress, onRelease
animate

Overview

SVGs are organized into layers, a tree of parents and children. In this example the rect is drawn last, on top of everything.

<svg>
 ┃
 ┣━ <g>
 ┃   ┃
 ┃   ┣━ <circle>
 ┃   ┗━ <path>
 ┃
 ┗━ <rect>

To draw a shape first ask yourself who is this shape's parent?

who-is-the-parent.circle(800, 600, 100)

The simplest arrangement is that every shape is a child of the SVG. This command creates an <svg> element.

const svg = SVG()

This creates an <svg> element and appends it to the body.

const svg = SVG(document.body)

This creates an <svg> with viewBox dimensions 800x600.

const svg = SVG(800, 600)

Drawing

To draw a shape first write the parent, followed by a ".".

svg.rect(width, height, x, y)
svg.circle(radius, x, y)

SVG shapes are circle, ellipse, line, path, polygon, polyline, rect, text

Nested layers looks like this:

const child = svg.g();
const grandchild = child.g();

Groups can manage layer order. In this example the circle will appear underneath the rect.

const layer = svg.g()          // layer
svg.rect(width, height, x, y)  // on top of layer
layer.circle(radius, x, y)     // child of layer, underneath rect

Shape-drawing parents are:

Style

Style is applied using method-chaining, camel-case svg attributes.

svg.line(0, 0, 300, 300)
  .stroke("#F08")
  .strokeWidth(3)          // stroke-width
  .strokeDasharray("5 3")  // stroke-dasharray

If a style is applied to a parent, all children will inherit that style unless a child overwrites it.

const layer = svg.g()
  .fill("none")
  .stroke("red");

layer.rect(width, height, x, y)
  .stroke("blue");

In the example above, the rectangle has no fill (inherited from layer) and a blue stroke (overwritten).

Events

svg.onPress = function (mouse) {
  // mouse press or mobile tablet screen touch
}
svg.play = function (event) {
  // animation frame based loop
}

Animation

if you are familiar with Processing or openFrameworks the animation works differently here. This is the basic form for a still frame:

svg.size(100, 100);
svg.background('transparent');
// draw here
svg.ellipse()

The basic structure for animations, Processing/openFrameworks style, you need the removeChildren at the beginning of the play() loop. Also the background is a child, so it needs to follow.

svg.size(100, 100);

svg.play = function (e) {
  svg.removeChildren();
  svg.background('transparent');
  // draw here
  svg.ellipse()
};

But even that's not the best approach. Better SVG drawing is to place the item on the screen before the loop and modify it's properties.

svg.size(100, 100);

var el = svg.ellipse();

svg.play = function (e) {
  svg.removeChildren();
  svg.background('transparent');
  // modify drawing here
  el.setCenter(...);
};

Methods

Certain shapes come with methods, see the methods section below. One notable example is the path element. Upper/lowercase for path methods reflects the specification.

svg.path()
  .Move(x1, y1)
  .line(x2, y2)
  .Curve(cx1, cy1, cx2, cy2, x3, y3)

SVG Onload

In my opinion, the best way to create an SVG is to use the function callback feature. This encapsulates your code in a function (good to do) and waits until the page has loaded.

SVG((svg) => {
  svg.size(window.innerWidth / window.innerHeight, 1);
  svg.rect(svg.getWidth(), svg.getHeight());
  ...
});

Appendix

Supported Nodes

svg, defs, desc, filter, metadata, style, script, title, view, cdata, g, circle, ellipse, line, path, polygon, polyline, rect, text, marker, symbol, clipPath, mask, linearGradient, radialGradient, pattern, textPath, tspan, stop, feBlend, feColorMatrix, feComponentTransfer, feComposite, feConvolveMatrix, feDiffuseLighting, feDisplacementMap, feDistantLight, feDropShadow, feFlood, feFuncA, feFuncB, feFuncG, feFuncR, feGaussianBlur, feImage, feMerge, feMergeNode, feMorphology, feOffset, fePointLight, feSpecularLighting, feSpotLight, feTile, feTurbulence

Supported Attributes

accumulate, additive, alignment-baseline, attributeName, azimuth, baseFrequency, baseline-shift, begin, bias, by, calcMode, color, color-interpolation, color-interpolation-filters, cursor, diffuseConstant, direction, display, divisor, dominant-baseline, dur, dx, dy, edgeMode, elevation, end, exponent, fill, fill-opacity, fill-rule, filter, filterRes, filterUnits, flood-color, flood-opacity, font-family, font-size, font-size-adjust, font-stretch, font-style, font-variant, font-weight, from, gradientTransform, gradientUnits, image-rendering, in, in2, intercept, k1, k2, k3, k4, kernelMatrix, keyPoints, keySplines, keyTimes, lengthAdjust, letter-spacing, lighting-color, limitingConeAngle, max, method, min, mode, numOctaves, opacity, operator, order, overflow, overline-position, overline-thickness, paint-order, pointer-events, pointsAtX, pointsAtY, pointsAtZ, preserveAlpha, preserveAspectRatio, primitiveUnits, radius, repeatCount, repeatDur, restart, result, rotate, seed, shape-rendering, spacing, specularConstant, specularExponent, spreadMethod, startOffset, stdDeviation, stitchTiles, strikethrough-position, strikethrough-thickness, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, surfaceScale, tabindex, targetX, targetY, text-anchor, text-decoration, text-rendering, textLength, to, transform-origin, type, underline-position, underline-thickness, user-select, values, vector-effect, visibility, word-spacing, writing-mode, xChannelSelector, yChannelSelector

Methods

Methods for individual element types

<svg>

clear()
size(x, y, w, h)
size(w, h)
setViewBox(x, y, w, h)
background(color)
getWidth()
getHeight()
stylesheet(css)
load(file)
save()

<path>

clear()
command(command, ...args)
get()
set(...)
add(string)

move()
line()
vertical()
horizontal()
ellipse()
curve()
smoothCurve()
quadCurve()
smoothQuadCurve()

Move()
Line()
Vertical()
Horizontal()
Ellipse()
Curve()
SmoothCurve()
QuadCurve()
SmoothQuadCurve()

close()

<polygon>, <polyline>

setPoints(...)
addPoint(...)

<marker>, <symbol>, <clipPath>, <mask>

size(...)
setViewBox(...)

<line>

setPoints(...)

<circle>, <ellipse>

radius(...)
setRadius(...)
center(...)
setCenter(...)
position(...)
setPosition(...)

Methods applied to most elements

removeChildren()
appendTo(...)
setAttributes(...)

translate(...)
rotate(...)
scale(...)
matrix(...)
clearTransform()

marker(...)
symbol(...)
clipPath(...)
mask(...)

addClass(...)
removeClass(...)
setClass(...)
setID(...)