SVG5: More Transforms and Composition

by Mike Gleicher on September 9, 2014

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).

edits: answering some student questions

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.

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

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

  1. 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).
  2. 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.
  3. 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).
  4. 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.
  5. If you don’t specify the origin of a rotation, it rotates about the origin.
  6. You should be able to figure out what order SVG applies the transformations in.   (spoiler: it’s the same convention we use in class)
Print Friendly, PDF & Email

Previous post:

Next post: