Skip to content

SVG

SVG (Scalable Vector Graphics) is a markup-based language similar to HTML, but for laying out images.

A simple SVG might look like:

<svg width="200" height="200">
    <circle cx="100" cy="100" r="50" fill="blue" />
    <circle cx="100" cy="100" r="50" stroke="red" />
</svg>

SVG is unitless, whereas in HTML and CSS we have to specify units like "300px" or "20em", SVG uses a unitless system so that it can be scaled to any size.

Units should be thought of as relative, if your graphic is 100x100, you know that the center point is at (50, 50).

The decision on how these virtual units convert to real-world units is made when you embed on an HTML page, in a PDF document, print, etc.

Coordinate System

As mentioned previously, computer graphics uses a top-left origin system by default.

The top left corner of an SVG is (0, 0) by default.

viewBox

On the root svg element, width and height control how the image appear in the context of the HTML page (if embedded directly).

viewBox controls the interior coordinate system. It takes four parameters separated by spaces: "minX minY width height".

Basic SVG Elements

Common Attributes

  • fill - interior color of drawn shape/path
  • stroke - exterior color of drawn shape/path

Not required attributes, but we'll use them in upcoming examples. (Can also be set via CSS styles.)

SVG defines tags for common shapes, each with a few required attributes.

Circle

  • cx & cy - used to define center of circle
  • r - radius

Rect

Required parameters:

  • width
  • height

Polyline, Polygon, and Ellipse

Take list of points. Difference is that polygon is closed loop & polyline is a continuous line.

Text

The text element has a lot of additional properties, and uses innerText between the tags to set the actual content:

MDN: SVG Text

Path

Finally, <path> is the most flexible SVG shape. We won't go into defining our own paths by hand, as you will usually use either a tool (like Inkscape) or a library (like d3) to lay out paths. They use a custom format to define specific movements, straight lines and curves.

Styling

Like HTML, styling can be done inline, with CSS classes, or external stylesheets.

Grouping and Transforms

We often have related objects that we want to keep together logically, and we can use <g> to create groups, and then apply transforms to these groups.

More SVG References