SVG2: Coordinate Systems

A newer version of these tutorials is available at: https://graphics.cs.wisc.edu/Courses/559-sp2021/tutorials/svg/

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

Now that you know that you’re going to have to use SVG, here’s a few things will be useful in actually making some pictures.

Remember that when you make the SVG tag, you need the magic parameter that tells the web browser that it really is SVG

<svg xmlns="http://www.w3.org/2000/svg">

If you forget the magic and cryptic xmlns="http://www.w3.org/2000/svg" the browser says “This XML file does not appear to have any style information associated with it. The document tree is shown below.”

In that same line, you should also tell thing how big your SVG picture is – the size of the “canvas”. These are the width and height parameters.

If I do this…

1<svg xmlns="http://www.w3.org/2000/svg">
2    <rect x="0" y="0" height="110" width="110" fill="#EEE"> </rect>
3    <rect x="10" y="10" height="40" width="40" fill="blue"></rect>
4    <circle cx="70" cy="90" r="30" fill="red"></circle>
5</svg>

I can draw anywhere – it might even let me draw out of the boundaries (since there aren’t any)

By specifying a width and height for the SVG object, we can put boundaries on the canvas

1<svg height="100px" width="100px" xmlns="http://www.w3.org/2000/svg">
2    <rect x="0" y="0" height="110" width="110" fill="#EEE"> </rect>
3    <rect x="10" y="10" height="40" width="40" fill="blue"></rect>
4    <circle cx="70" cy="90" r="30" fill="red"></circle>
5</svg>

Notice that he coordinate system is not changed by the change of size of the canvas. By default, the coordinate system in SVG has (0,0) at the top left, and x and y each be in the default units of the canvas. When you give a size for the canvas, it assumes those are the units you want to use. Here, I specified pixels (that’s why it’s height="100px").

SVG allows us to specify a different coordinate system for the canvas as another parameter to the SVG tag. It takes as a parameter a string with 4 numbers in it. The minimum values for x and y and the maximum values for x and y. So, if we wanted the first picture squished into the boundaries of the second, we could do:

1<svg viewbox="0 0 120 120" height="100px" width="100px" xmlns="http://www.w3.org/2000/svg">
2    <rect x="0" y="0" height="110" width="110" fill="#EEE"> </rect>
3    <rect x="10" y="10" height="40" width="40" fill="blue"></rect>
4    <circle cx="70" cy="90" r="30" fill="red"></circle>
5</svg>

You could have achieved the same effect (getting a convenient coordinate system) by putting computing a transformation that you apply to the group of objects. But, transformations and groups are the next tutorial.

There are some more other technical things that come up with SVG coordinate systems, these are discussed in the SVG documentation, but are not so important for the class.

Next: SVG3: Manipulating Primivites
Prev: SVG1: Getting Started with SVG