Vector.js

Vector is an open source javascript library for creating interactive graphics. View the repository, run the tests, or meet the team.

SVG Tutorial

This tutorial is intended to give the reader an interactive introduction to using and authoring SVG documents. See the working group’s W3 SVG Overview for the specification. Another good tutorial and reference is the MDN SVG Tutorial. See also the list of SVG Elements.

Getting Started

SVG stands for scalable vector graphic and represents a standard for vector/raster graphics. Elements within the SVG document are defined using XML syntax. Every element has an opening tag and closing tag. The opening tag contains the elements name surrounded by angle brackets. The closing tag contains the elements name with a forward slash before it also surrounded by angle brackets. For example, the “svg” tag which forms the root of the document looks like:

<svg></svg>

Elements have attributes that describe additional details about the element. Attributes are defined within the opening tag and have a name and string value. For example, if we have a attribute named data which is associated with the string “123” this would look like: data="123". The svg element should have a xmlns atrribute which defines the xml name space to be used, and often has a width and height attribute defined. This can be seen in the SVG image below which also defined a circle element with the attributes cx, cy, and r.

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">
    <circle cx="50" cy="50" r="15"></circle>
</svg>

The SVG document above is rendered as:

XML Syntax

XML elements are formed by opening and closing tags. The opening tag contains a name followed by space separated attributes. Attributes define additional information about the element and are in the form of name=“value”.

Within the SVG Namespace elements have geometric properties that are represented using attributes to describe the shape and form of the element. Elements often have attributes that are specific to the element, but there are also more general attributes that are useful and which can be applied to any element. For example, the following three attributes are very useful for retrieving and/or styling elements.

attribute description
id unique string identifier
class list of classes separated by spaces
style inline styling for this element

Tree Structure

A SVG document is structured like a tree. Every SVG element has an opening and closing tag. Within the tags is where child elements are placed. These children inherit the coordinate system and styles of the parent element. (TODO: double check these facts)

<svg>
  <rect></rect>
  <circle></circle>
</svg>

In the example above, the SVG element has two children: a rectangle and circle. The ordering of the elements matters. In this example the circle is rendered on top of the rectangle, because the circle is placed after the rectangle within the SVG document.

Basic Elements

The basic visual elements such as the line, ellipse, rectangle, etc and structural elements such as the svg element and group element form the look and feel of the final image.

Line Element

An interactive SVG line element.

Properties

Name Description
x1 The x component of the starting point of the line
y1 The y component of the starting point of the line
x2 The x component of the ending point of the line
y2 The y component of the ending point of the line

This interactive demonstrates the properties of the SVG line element.

Ellipse Element

Interactive SVG ellipse element.

Properties

Name Description
cx The center x position of the ellipse
cy The center y position of the ellipse
rx The x radius of the ellipse
ry The y radius of the ellipse

Rectangle Element

An interactive SVG rectangle element.

Properties

Name Description
x The x-position of the top-left point of the rectangle.
y The y-position of the top-left point of the rectangle.
width The width of the rectangle.
height The height of the rectangle.

This interactive demonstrates the properties of the rectangle element. There are two controls: one that changes the (x,y) position of the rectangle, and another that changes the width and height attributes.

Group Element

A group is a structural element, useful for applying styles and transformations to multiple elements at once. This element and others are discussed in more detail later in this tutorial.

Path Element

The path element is powerful and complex and deserves its own section. The path's shape is described by a series of commands and points. The command describes how the points should be used to draw the path.

Properties

Name Description
d A series of commands that draw the path.
pathLength The length of the path.

The path element is notorious for its power and difficulty. The path element has one attribute, the “d” attribute, which is a string containing a series of commands. Each command starts with a letter that describes the type of command followed by zero or more numbers separated by spaces.

<path d="..."></path>

Commands

Name Syntax
Move To M x y
Line L x y
Quadratic Bezier Q x1 y1 x2 y2
Cubic Bezier C x1 y1 x2 y2 x3 y3
Arc A rx ry x-axis-rotation large-arc-flag sweep-flag x y
Close Z

Path: Move To Command

Every path starts with a move command which describes where the path starts. A path can have multiple move to commands to start drawing the path elsewhere in the document.

Path: Line Command

<path d="L x y"></path>

In the path below, the move command “M 150 150” begins the path at the coordinate (150, 150) and then the line command “L 450 50” draws a line to the coordinate (450, 50). Note, commands have the option to be absolute, represented with a capital letter, or relative, represented with a lowercase letter.

Path: Quadratic Bezier Command

<path d="M x0 y0 Q x1 y1 x2 y2"></path>

The quadratic bezier curve command draws a curve between two points: the current position of the path and the end point (x2, y2). The shape of the curve is described by the first position in the command (x1, y1). Mathematically the curve is a parameterized polynomial. More info here.

Path: Cubic Bezier Command

<path d="M x0 y0 C x1 y1 x2 y2 x3 y3"></path>

The cubic bezier curve command is like the quadratic curve with an additional point to further control the shape of the curve.

Path: Arc Command

<path d="M x0 y0 A rx ry x-axis-rotation large-arc-flag sweep-flag x y"></path>

The arc command draws an arc between two points. The syntax of the command is “A rx ry x-axis-rotation large-arc-flag sweep-flag x y”. The arc is drawn between the current position of the path and the end position (x,y). The numbers rx and ry define the shape of the ellipse which forms the arc. The x-axis rotation number controls what part of the ellipse’s arc is being drawn between the points. The large arc flag determines whether to take the shorter arc or longer path between the two points. Finally, the sweep-flag chooses which of the two ellipsis that pass through the two points to draw.

Coordinate System

The origin of the svg coordinate system is at the top-left corner of the image. The positive x-direction is to the right and the positive y-direction is down. In the world of computer graphics it is standard to have the y-axis flipped since elements are positioned relative to the top-left corner of the container. Try clicking and dragging the control point below.

View Box

<svg viewBox="minX minY width height"></svg>

The view box attribute allows the user to define a view port of the image. This means defining where the origin is and the relative dimensions: width and height to be displayed. For example, if we want to zoom in on the geometric shapes below we can apply a viewbox which is visualized with the rectangle on the left. The resulting svg is shown on the right.

<svg viewBox="130 100 350 200">
  <!-- colorful squares ... -->
</svg>
<!-- TODO: preserve aspect ratio attribute -->

Transforming

SVG elements have the ability to have a transformation attribute defined that can transform the element geometrically.

Scale

Elements can be scaled to larger or smaller sizes by adding a scale function to the transform attribute.

<g transform="scale(x,y)">
  <!-- elements to be scaled ... -->
</g>

Rotate

Elements can be rotated.

Translate

Elements can be moved to new locations.

Chaining Transformations

Other Transformations

Styling

SVG elements are styled using Cascading Style Sheets or CSS for short. Styling can be applied to individual elements as inline style, defined in a <style> tag within the SVG document, or defined externally in a .css file. There are many different styles that can be applied to each element. Two of the most basic are the fill and stroke color.

Inline Style

Styling can be applied to individual elements using the style attribute. This is very useful for testing out different styling on an element, but in practice it is better to use CSS selectors to style elements based on id, class, and tagname.

<svg xmlns="http://www.w3.org/2000/svg">
  <circle cx="150" cy="75" r="50" style="fill:purple;"></circle>
</svg>

Style Element

CSS rules can be applied in the style element within the SVG document. A CSS rule applies styling to elements that match the selectors before the style enclosed in the curly braces. In the example below the selector “circle” will be applied to all circle elements within the SVG.

<svg xmlns="http://www.w3.org/2000/svg">
  <style>
  circle {
    stroke:purple;
    stroke-width:1px;
    fill:none;
  }
  </style>
  <circle cx="150" cy="75" r="50"></circle>
</svg>

Effects

Styling can be applied to a specific element state such as “:active”, “:focus”, “:hover”. For example when the user hover’s over the circle below additional styling is applied to make the fill of the circle darker.

#my-circle:hover{
  fill:cornflowerblue;
}

Typography

This section of the tutorial deals with creating and formatting text within SVG documents.

Text Element

The text element defines text with an x, y position in the document.

<text x="75" y="75">The quick brown fox jumps over the lazy dog.</text>

Tspan Element

The text span element is useful for changing the position and or the styling of a piece of text within a text element. In the example below, the first word is placed within a tspan element and bolded to emphasize the word. Then, later, a tspan element is positioned relative to the last tspan element.

<text id="tspan-example" x="32" y="75" >
  <tspan>"</tspan>
  <tspan style="font-weight:600;">Fly </tspan>
  <tspan>you fools.</tspan>
  <tspan>"</tspan>
  <tspan dx=20 dy=30>Gandalf the Grey</tspan>
<text>

Horizontally Align Text

The “text-anchor” attribute allows you to horizontally align text relative to its position. This is demonstrated below in the SVG, the red dot represents each text elements position.

text-anchor:left;
text-anchor:middle;
text-anchor:right;

Vertically Align Text

The “alignment-baseline” attribute allows you to vertically align text relative to its position. This is demonstrated below in the SVG, the red dot represents each text elements position.

dominant-baseline:baseline;
dominant-baseline:middle;
dominant-baseline:hanging;

Superscript and Subscript

<!-- superscript & subscript text -->

Auto Wrapping

<!-- auto wrapping -->

Preformated Text / Line Breaks

<!-- pre-formated / line breaks -->
// how to convert typography to paths?

Advanced Elements

The SVG specification has a lot of elements, and while not all are covered in this tutorial, there are a couple of advanced elements worth mentioning.

Clip Path

Clip paths can be applied to elements to show only the part of the graphic contained within the shape of the clip path. The clip path is applied to an element and its children by setting the clip-path attribute to point to a clip path element in the DOM tree.

<g clip-path="url(#my-clip-path)">
  <!-- grid of rectangles ... -->
</g>
<clipPath id="my-clip-path">
  <circle cx="300" cy="150" r="50"></circle>
</clipPath>

Click and drag the clip path below to change the position of the circle that defines the clipping path.

Defs

The defs element contains a graphical “definition” that can be used else where in the document. This is useful for arrows at the start and end of a path, adding markers along a path, or creating a pattern of repeated images.

<!-- adding markers / arrows to a path -->
<!-- adding gradient / pattern to a shape -->

Scripting

It is common to extend the functionality of SVG documents by adding scripting to make them interactive. This section demonstrates how to use vanilla Javascript and Web APIs to create, manipulate, and add interactivity to SVG elements. There are many libraries and frameworks to help with this very thing. This library vector.js is one of them.

Creating SVG Elements

To create a SVG element within a simple static web page using javascript: first, you create an element using the W3 namespace and add it into the document object model or DOM for short. This example demonstrates generating a SVG element and adding that to a container element in the HTML page. Then creating a circle element and adding that to the SVG element.

// Get an element in the DOM to append the svg into
let container = document.getElementById("container");

// Creates a root svg element and appends it into HTML the container
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("width", "720px");
svg.setAttribute("height", "200px");
container.appendChild(svg);

// Creates a circle element and appends it into the svg element
let circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100");
circle.setAttribute("cy", "100");
circle.setAttribute("r", "50");
svg.appendChild(circle);

This script needs a corresponding HTML file to run. Note that there is a div element with the identifier “container” and a script element that loads in the script above.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Create Element</title>
  </head>
  <body>
    <div id="container"></div>
    <script src="./create-element.js"></script>
  </body>
</html>

Placing these to files in a folder together and opening the HTML file in a web browser results in the following SVG.

Selecting Elements

// select element by id
let element = document.getElementById("my-element-id");
// select elements by tag
let elementList = document.getElementsByTagName("circle");
// select elements by class
let elementList = document.getElementsByClassName("my-class");

Manipulating Attributes

element.setAttribute("some-attribute", "some-value");
element.getAttribute("some-attribute");
element.classList.add('my-class');
element.classList.remove('my-class');

Manipulating Style

// access style property for inline styling

Useful Functions

// get bounding client rectangle
// SVGGraphicsElement getBBox();

Basic Interactive

Interactivity allows for user input to change the SVG document. The most basic form of this is register handlers to user events. Handlers are registered to specific elements and are called when the event takes place. Examples of events are the mouse click event, mouse move event, mouse over element event, keyboard events, and more.

// TODO: interactive that displays types of event handlers being called
// Maybe some basic shapes with colors

Registering an Event Handler

// register event listener

SVG Scripting Libraries