Nino's Blog

SVG tutorial

2020-05-10

SVG basics

Basic SVG shapes

<svg x="0px" y="0px" width="600px" height="400px" viewBox="0 0 600 400">
  <rect x="10" y="5" width="100" height="100" stroke="black" fill="white" />
  <circle cx="50" cy="50" r="10" stroke="black" fill="white" />
  <polygon points="234, 334,43, 100, 321,21, 234" stroke="black" fill="white" />
  <line stroke="black" fill="none" x1="350" y1="100" x2="450" y2="200" />
</svg>

width, height - If you don’t specify width and height it will be 100% (fill the container).
viewBox - x, y, width, height (just like Element.getBoundingClientRect())

Svg are responsive by default.
html

<svg viewBox="0 0 600 400"></svg>

css

svg {
  width: 600px;
}
/* Double the size  */
svg {
  width: 1200px;
}

If we remove elements out of the viewbox, it will be cut out, we can clip things on the fly. Unlike jpeg, where things outside are removed, in svg they still exists, but you can’t see it.

preserveAspectRatio attribute indicates how an element with a viewBox providing a given aspect ratio must fit into a viewport with a different aspect ratio - default value “xMidyMid Meet”. Meet - entire viewBox is visible within viewport. ViewBox is scaled up as much as possible. Slice - entire viewport is covered by viewBox (cut off). ViewBox is scaled down as much as possible. None - do not force uniform scaling.

group and path

g - group, like a div. If you have a car that consists of many shapes and you want to move it, you group it with g and move just that group, instead of all shapes. Attributes, including classes, on g element will apply to all child elements.

path

<path d="M10, 20, 30, 40-50z" />

Capital letter for absolute position, lowercase relative from current position.

  • M/m - move to

Line commands:

  • L/l - line to
  • H/h - horizontal line from current position
  • V,v - vertical line from current position
  • Z/z - to close path, from current position to beginning

Curve commands:

  • C/c - cubic-bezier
  • S/s - reflecting cubic-bezier
  • Q/q - quadratic cubic-bezier, where both sides share same control
  • T/t - command control point that’s been reflected
  • E/e - elliptical arc Great codepen site to explore how path works - https://codepen.io/anthonydugois/full/mewdyZ

    polyline - just like polygons
<polyline points="10,20, 40,50, 70,34 />

a11y

<svg aria-labelledby="title" id="svg" role="presentation">
  <title id="title" lang="en">Icon that illustrates rise of ...</title>
</svg>
  • Title for elements in SVG DOM.
  • Role to let screen reader knows what to traverse (presentation - don’t read everything in SVG DOM, role can also be image)

Playgrounds

Sources:


Written by Nino Majder who lives and breaths web development. Follow him on Twitter