SVG in HTML5
Coordinates and Positioning in SVG
In this chapter, we will learn how the coordinate system works in SVG and how to position elements precisely. Understanding the coordinate system is fundamental for creating organized and controlled graphics, especially when working with complex graphics or animations.
The Coordinate System in SVG
The coordinate system in SVG uses an X-axis and a Y-axis, similar to the Cartesian coordinate system. By default, the origin (0,0) is located at the top-left corner of the SVG area. This means that the x
value increases to the right, and the y
value increases downward.
html
The previous code defines two circles in different positions, illustrating how the cx
and cy
coordinates work within the SVG space.
Units and Scaling in SVG
SVG allows different types of units, such as pixels (px
), points (pt
), and percentage (%
). The choice of units can affect how the graphic scales on different screens or when the SVG area is enlarged.
html
In this case, the rectangle will adjust to the width of the container where the SVG is included, being flexible and adapting to the available size.
ViewBox: Controlling the Viewing Area
The viewBox
attribute is one of the most important in SVG for defining a "window" through which the SVG content is observed. viewBox
allows us to scale and adjust the content independently of the physical size of the SVG.
The syntax of viewBox
is:
html
min-x
andmin-y
: Coordinates of the top-left point of the visible area.width
andheight
: Size of the view.
Example with viewBox
html
This viewBox
of 0 0 100 50
establishes a view that only shows a portion of the total area, allowing the circle to scale based on that reduced space.
Adjusting the Origin and Coordinate Axes
In SVG, it is possible to modify the origin and orient the axes using transformations. This is especially useful when creating complex graphics or animations that require a change in the coordinate system reference.
Example of Transformation with translate
html
In this example, the <g>
group applies a translate
transformation that moves the rectangle to a new position. This allows adjusting the position of elements relative to a specific point within the SVG area.
Conclusion
The coordinate system in SVG is a fundamental aspect for designing precision graphics. From the use of units and scaling to the control of the view with viewBox
, these concepts are essential for any developer working with SVG on the web. In the next chapter, we will explore how to apply styles in SVG with CSS, allowing us to enrich the visual appearance of our graphics.
See you in the next chapter!