SVG5: More Transforms and Composition

(Note: this is copied over from 2014, without much modernization)

Most of the things I’ve seen about SVG on the web are meant for designers who haven’t had a graphics class, so they are a little vague about transformation. The specification actually has all the details (including all of the kinds of transforms that are supported), but there’s a lot to read through until you get to the relevant parts (skip to here).

For seeing how the individual transforms work, there is a great demonstration here where you can try all of the individual transformations and adjust their parameters. It doesn’t help so much to see how they compose. This tutorial gives the actual equations, and an example of composition (by using hierarchies).

Here is a simple example that uses composition without hierarchies. From it, you should be able to see how the order or transformations matters. You should understand why the blue and green stroked squares end up where they do.

 1<svg xmlns="" xmlns:xlink="" height="300px" width="300px" viewBox="-100 -100 200 200">
 2<!-- create the group - draw it untransformed so its not in a def -->
 3<g id="square">
 4    <rect x="-10" y="-10" height="20" width="20" fill="#cab2d6" stroke-width="0" />
 5    <polygon points="0,0 0,-10, 10,0" fill="#6a3d9a" stroke-width="0" />
 6    <rect x="-10" y="-10" height="20" width="20" fill="None" stroke-width="3" />
 8<!-- the same two transformations, just in different order -->
 9<use transform="translate(50,0) rotate(45)" stroke="blue" xlink:href="#square" />
10<use transform="rotate(45) translate(50,0)" stroke="green" xlink:href="#square" />

A few things to make interpreting the SVG for this diagram a little easier (and tricks for your own experiments):

  • Notice how I use the “viewBox” parameter to the SVG file to set up a coordinate system with zero at the center. It took a little trial and error for me to figure out that the viewBox parameters are left, right, width, height. With what I did, the zero point is 100 units from the left (or top) edge (at -100), which is half of the width (or height).
  • Notice how I have the little mark in the upper right corner of the square so that its not symmetric, and you can tell how much things have been rotated by.
  • Because I did not define the color of the stroke on the last square, it can inherit the color from its group (or from the “use” statement that instantiates it).
  • Notice that rotations in SVG’s standard coordinate system are clockwise. Since the Y axis goes down (not up like in a math class), this is still a right handed coordinate system.
  • If you don’t specify the origin of a rotation, it rotates about the origin.
  • You should be able to figure out what order SVG applies the transformations in. (spoiler: it’s the same convention we use in class)

Next: SVG6: Curves in SVG
Prev: SVG4: Groups, Transforms, Re-Use, and Hierarchies