How to use the viewBox property
How to move the origin of the coordinate system
In the previous chapter, we defined the SVG element with its width
and height
properties. These properties define how much space the image takes up in the browser. Without further properties, the coordinate system for the image is also derived from these two. It starts at 0,0
at the top-left corner and grows one pixel at a time downwards and right.
We can move the origin of the coordinate system by setting the viewBox
property. For this property, we need to set four numbers. The first two are the position of the top-left corner. If we set it to -100,-100
, the origin will end up in the middle of the image. The image elements will position themself compared to this new origin.
How to scale the image
The last two numbers in the viewBox
property define the image’s inner size from the image elements’ perspective. If these values match the width and height, then one pixel on the screen will be one unit within the SVG image.
If these values do not match, the image elements scale down or up. Below, we define the same rectangle as in the previous examples, but it appears to be bigger this time. This is because while the image’s actual size did not change, the image elements now think of the available space as a 100 x 100 grid.
How to draw a Christmas Tree with SVG
For the following example, let’s move the origin of the coordinate system to the middle of the image. This way, every position we define is relative to this midpoint.
In this example, we will use the polygon
element. A polygon is the easiest way to draw a freeform shape. Polygons have a points
property that sets a list of coordinates that are connected with straight lines.
We can me the crown of the tree from three triangles. We start with the one at the bottom, and we add it layer by layer.
Finally, we add the trunk of the tree as a rectangle.