SVG for Webpages

Personal Log 2021-02-03

Following some of this blog post.



The viewBox attribute of the svg element specifies what space we have to draw in (the size of the canvas). The width and height attributes scale the contents of the viewBox to any arbitrary size without loss of image quality.

Here is an example of an svg element that is 10x10 units in size, that has been scaled by a factor of 10 to 100x100 pixels.

(0, 0) x-axis (10, 0)
y-axis
(0, 10) (10, 10)

SVG Lines

An svg line requires two coordinates: a starting position and an ending position, denoted as (x1, y1) and (x2, y2). These positions are specified relative to the viewBox; the current viewBox is set to 10x10.

Stroke

Here is an example where the svg element has a border consisting of 4 lines. The stroke attribute can be used to specify the line colour (either inline or in the css).

Drawing is executed from top to bottom. To change which colour is drawn last (i.e. shown on top), we can modify the positions of the lines. Placing the red line in the 2nd and 3rd positions will result in the following:

Stroke Width

The stroke-width has a default value of 1 and specifies the width of the lines being drawn. For lines on the edge of the viewBox, the stroke-width is effectively halved, as the stroke-width is centred on the line.

Stroke Linecap

The stroke-linecap specifies how the line is terminated. The options are:

The circumference of the circle cap and the width of the square cap are equal to the stroke width. Each cap is centred on its corresponding coordinate. In the example below, each line has 2 caps, one for each coordinate. Using a square or circle cap effectively adds 1xstroke-width units of length to the line.

Example Line Icons

Polyline

A polyline can be used to create a drawing consisting of multiple, contiguous line segments. The svg is written to indicate each coordinate of the polyline:
x1 y1, x2 y2, ..., xn yn.

In the example below, the black content shows the css property for fill, whereas the aquamarine content shows the css property for background-color.

Stroke Linejoin

Similar to stroke-linecap, the stroke-linejoin attribute specifies the behaviour at the point of intersection for two lines. A change is only noticable if the lines form an angle not equal to 180°. The options are:

SVG Circles

An svg circle consists of a centre point (cx, cy) and a radius (r).

Dynamic Circles

The examples below will dynamically change the svg depending on the position of the cursor inside the element.

Circle moves with cursor position

Circle's radius matches cursor position

Example Circle Icons

SVG Shapes

Polygons

An svg polygon is the same as a polyline, except the last and first point are connected with a line.

Rectangles

Rectangles can be drawn in a similar way to circles using rect, if not using polygon. The point (x, y) represents the top right corner of the rectangle.

Example Shape Icons