SVG:2 Coordinate Systems

by Mike Gleicher on September 4, 2014

Now that you know that you’re going to have to use SVG (from this), here’s a little that 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…

<svg xmlns="http://www.w3.org/2000/svg">
	<rect x="0" y="0" height="110" width="110" fill="#EEE"> </rect>
    <rect x="10" y="10" height="40" width="40" fill="blue"></rect>
    <circle cx="70" cy="90" r="30" fill="red"></circle>
</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

<svg height="100px" width="100px" xmlns="http://www.w3.org/2000/svg">
	<rect x="0" y="0" height="110" width="110" fill="#EEE"> </rect>
    <rect x="10" y="10" height="40" width="40" fill="blue"></rect>
    <circle cx="70" cy="90" r="30" fill="red"></circle>
</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:

<svg viewbox="0 0 120 120" height="100px" width="100px" xmlns="http://www.w3.org/2000/svg">
	<rect x="0" y="0" height="110" width="110" fill="#EEE"> </rect>
    <rect x="10" y="10" height="40" width="40" fill="blue"></rect>
    <circle cx="70" cy="90" r="30" fill="red"></circle>
</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.

Print Friendly, PDF & Email

Previous post:

Next post: