SVG Tutorial - Coordinate System

Subscribe Send me a message home page tags

#svg  #tutorial  #coordinate system  #transform  #flip 

In this post, we discuss how to work with SVG images.

First, let's create a simple svg image. The following code creates a SVG image width width = 300 and height = 200.

<svg version="1.1" width="300" height="200" xmlns="">
    <rect width="100%" height="100%" fill="#9fcfff" />
    <circle cx="20" cy="20" r="5" fill="#f6423a" stroke="None" />
    <text x="20" y="40", font-size="10", text-anchor="middle", fill="#f6423a">(20, 20)</text>
    <circle cx="50" cy="80" r="5" fill="#f6423a" stroke="None" />
    <text x="50" y="100", font-size="10", text-anchor="middle", fill="#f6423a">(50, 80)</text>
    <circle cx="180" cy="150" r="5" fill="#f6423a" stroke="None" />
    <text x="180" y="170", font-size="10", text-anchor="middle", fill="#f6423a">(180, 150)</text>
(20, 20) (50, 80) (180, 150)

It's worth effort to make the coordinate system clear: The origin (0, 0) is the top left.


A quick note on the different coordinate systems. They can be very confusing from time to time:


In general, it's better to make coordinate systems use the same convention. One way to do this is to flip the image. We can add

transform="scale(1, -1)" to the svg tag to flip the Y-axis. For example:

<svg version="1.1" width="300" height="200" xmlns="" transform="scale(1, -1)">

One of the issues is that this flips texts as well. Apparently, there is another coordinate system that is used when humans interprete visual information. For example, when we talk about up vs down or north vs south, we kind of assume there is an absolute coordinate system.

A simple fix would be when we create texts in svg, we flip them in the first place. Later, when we flip the entire svg image, those texts will be flipped back to a human-readable format.

Suppose we want to put a text at (20, 170). To flip it against Y-axis, we can do

<text x="0" y="0" font-size="20" text-anchor="middle" transform="scale(1,-1) translate(20, -170)">My Text</text>

(A quick note on the scale and translate operator. It seems that \(scale \cdot translate\) gives the final coordinates in the original canvas.)

Put everything together, we have the following figure. The small yellow dot is the location that is set for the text. As we can see, the text overall is "above" the location.


As we can see in this post, working with different coordinate systems at the same time can be confusing and challenging. On the other hand, these details should be hidden in the code and should not be felt at business logic level. At the end of the day, elements drawn on canvas is just a presentation of objects, which should be decoupled from the abstract concept.

----- END -----

If you have questions about this post, you could find me on Discord.
Send me a message Subscribe to blog updates

Want some fun stuff?