Sara Soueidan explores how scalable vector graphics can be used for much more than just creating and animating shapes.
An SVG graphic can contain basic shapes, complex shapes, or both. There are six basic shapes defined in SVG <circle>, <ellipse>, <line>, <polygon>, <polyline> and <rect>.
Each shape is described, positioned and styled using SVG ‘presentation attributes’. For example, the attributes used on each of the elements in the following snippet are all SVG presentation attributes:
<circle cx="100" cy="200" r="250" /> <!-- cx, cy position the circle's centre on the x and y axes, and r specifies the size of the circle's radius. All three are presentation attributes --> <rect x="300" y="100" width="400" height="220" /> <!-- x, y, width and height are presentation attributes used to position and size the rectangle --> <line x1="100" y1="300" x2="300" y2="100" stroke-width="5" /> <!-- the stroke-width presentation attribute sets the thickness of the line -->
In addition to the basic shapes, you can create complex shapes using the SVG <path> element. An SVG <path> has a presentation attribute d – short for ‘data’ – which contains the data that defines the outline of the shape you’re drawing. The path data consists of a set of commands and coordinates that tell the browser where and how to draw the points, arcs and lines that make up the final path
Here’s an example of an SVG <path>:
<path d="M 100 100 L 300 100 L 200 300 z" fill="deepPink" stroke="#009966" stroke-width="2" />
The above path draws a rectangle by moving M to the point (100, 100), drawing a line L to the point (300, 100), then drawing another line to the point (200, 300), and closing the path z to form a triangular shape. You can learn more about the SVG <path> syntax in this article by Chris Nager – or in the SVG specification.
In most cases, when you’re working with complex SVG graphics you’re likely to create these shapes in a graphics editor like Illustrator or Inkscape, then export the entire graphic as an SVG, and embed it into your page.
At first glance, exported SVGs may seem tricky because they contain a lot of code that seems intimidating at first. However, editors usually include meta data, comments and extra elements that can be safely removed without affecting the rendering result of your SVG.
As such, it is generally a good idea to optimise your SVG using one of the several optimisation tools available, to make the code cleaner. I would recommend Peter Collingridge’s online SVG editor, or the node.js-based tool SVGO. After optimising the SVG, it becomes much more readable and – more importantly – smaller.