SVG coordinate system

2021.07.25 “fireworks” coming, wind and rain masterpiece. Sitting around at home is no fun. Then I combed the content related to SVG coordinate system to pass the time.

The first three examples in this article are relatively simple, and the code from Example 4 is shown here.

HTML coordinate system

The coordinate system is used to locate and determine dimensions.

Positions are represented by tuples (coordinates) (x, y), and coordinates must require an origin.

Size is expressed by tuple (width, height), there must be a size unit, used to represent the graphics in the real world (for computer graphics system – display) size.

When using the browser to display elements, all coordinates are positioned based on the top left corner of the browser viewport. The browser’s rendering engine will calculate the position, size (layout) and color (draw) of an HTML element according to the CSS style rules of the page element. < SVG >
as an HTML element tag is no exception, so the display position of SVG is first determined by the position of the SVG tag in the HTML document flow.

Here are some examples:

  • The origin is in the upper left corner of the screen
  • The SVG element coordinates are (100, 300) 100 from the left edge of the screen, 300 from the top edge, 300 width, and 150 height

One important element missing from the above statement is the unit, without which these values are meaningless. We know that both SVG and HTML default to px units, CSS supports other units that can eventually be converted to PX by a certain rule. However, CSS PX is not the real pixel of the physical device. Window. devicePixelRatio defines the conversion relationship between the real pixel of different devices and CSS PX. So the unit conversion logic for a Web page might look something like this:

graph LR
  otherUnits[css units other than px]
  pxCss[css unints in px]
  pxPhysical[px of physical device]
  otherUnits -->|CSS rules| pxCss
  pxCss -->|devicePixelRatio| pxPhysical
  

By adding units, the positions and dimensions of the SVG elements in the previous figure are completely determined.

In the discussion below, unless otherwise specified, PX refers to CSS pixels rather than physical pixels.

SVG coordinate system

SVG elements are placed in the FLOW of HTML documents, so the positioning and dimensions of the element itself are determined by the HTML standard. **SVG coordinate systems are used to determine the positioning and dimensions of elements within SVG, and the units of coordinates and dimensions may not be fixed. ** The latter is the root cause of Scalable SVG.

Take the following SVG for example

<svg width="200" height="150" viewBox="0 0 200 150">
	<rect x="20" y="20" width="100" height="50" stroke="red" fill="white"/>
</svg>
Copy the code

The SVG is rendered as follows:

The SVG tag uses CSS to add an orange border for visual reference

Case 1

From the attributes of the recT tag, it is easy to know that the coordinates of the top left corner of the rectangle are (20, 20), and that the width of the rectangle is 100 and the height is 50, without units. The positive direction of the horizontal axis is → and the positive direction of the vertical axis is ↓.

So the question is what are the units of these numbers?

To answer this question, let’s first answer another question: What is the width and height of an SVG element, in units?

The answer is simple, just do a quick Google search and you will see that the width and height attributes of the SVG tag specify the width and height of an SVG element, in px. The answer is 200px, 150px.

So the answer to the first question is px.

That’s right, but it’s not that simple. We see that the SVG tag also has a viewBox property with a value of “0, 0, 200, 150”. In the example above, if the viewBox property is not specified, the default is 0 0 svgWidthInPx svgHeightInPx. Before explaining what this means, let’s look at two examples of changes that should give us a sense of what these four numbers mean.

viewBox="-100 -75 200 150"

Changed the first two values of the viewBox, reducing the SVG width and height by half, respectively. The rectangles have not changed their dimensions, but have been shifted 100px to the right and 75px to the bottom.

Case 2

viewBox="0 0 100 75"

Changing the last two values of the viewBox to half its original size makes the rectangle seem to have doubled in width and height. Some of them are already beyond the visual scope of SVG and have been pruned.

Example 3

What does a viewBox do

The viewBox exists to set up a coordinate system within SVG against which all elements within an SVG element are positioned and sized. You have to have an origin when you’re talking about a coordinate system. To map the position and length of a coordinate system to the real world, a coordinate system must have units.

  • Origin:SVG (Orange boxThe coordinates of the upper left corner are determined by the first two values of the viewBox, which deduce the origin.
    • In example 1, the upper-left corner of SVG is the origin(0, 0)
    • In Example 2, the upper-left corner of SVG is(100, 75)It can be inferred from this(0, 0)The dot is in the center of the SVG element
    • If the viewBox aspect ratio is not the same as the SVG aspect ratio, the origin is determined bypreserveAspectRatioJoint decision
  • unitThe last two values of the viewBox represent how many horizontal and vertical portions of the SVG are divided by the coordinate system, and the length of each portion can be calculated from the true width and height of the SVG
    • In example 1, the true width is 200px, and if it is horizontally divided into 200 pieces, each piece is 1px, so all values in SVG are horizontally divided by 1 unit.
    • Case 2. The true width is 200px, and if it is divided horizontally into 100 pieces, each piece is 2px, so the width of the rectangle is 100*2px, which is double the length of the profit.
    • The height units are similar. The aspect ratio of a viewBox can be different from that of SVG, and the dimension units for vertical and horizontal dimensions can be different (seepreserveAspectRatioSection).

In summary, viewBox=”x, y, w, h”, establishes a coordinate system on the SVG element. The upper-left coordinate of SVG is (x, y) and the lower-right coordinate is (x+w, y+ H). The determination of units of length for each unit in the coordinate system depends on the width and height properties of SVG and the preserveAspectRatio properties.

preserveAspectRatio

In the above example, the coordinate system created in the viewBox corresponds to the CSS dimensions (PX) because, in addition to the fact that the dimensions of the SVG elements are already specified, SVG’s preserveAspectRatio has a default value xMidYMid meet.

Why do we need this property?

In the example above, the viewBox has the same aspect ratio as the SVG element: 4:3. So we can easily get horizontal and vertical units of dimension. Example 1 is 1px, and Example 2 is 2px, and the horizontal and vertical are equal. But what if they have different aspect ratios?

Let’s start with the following example.

<ViewBox
  width='400'
  height='300'
  viewBox='0 0, 100, 100'
  preserveAspectRatio='xMidYMid meet'
/>
Copy the code

The following figure is displayed:

Example 4

The SVG element is a rectangle with a 4:3 aspect ratio, whereas the viewBox is a square. So what is the origin of the frame that the viewBox is creating, and what are the dimensions.

It is obvious from the figure above that the vertical viewBox is full of SVG elements, while the landscape is centered in SVG and the width is the same as the height (square, for example).

Back up, let’s look at the default value of the preserveAspectRatio property, xMidYMid meet. What this value means is

  • The size of the viewBox is determined by the relative length of the edge of the viewBox that fills the SVG in the corresponding direction. For example 4, the relative length of the viewBox is vertical, so the height fills the SVG. So the units in the coordinate system are (150/100 = 1.5px).meetPart of it determines this characteristic.
  • Once you’ve determined the units, you can figure out the actual length of the viewBox’s shorter edges compared to SVG. For example 4, the shorter edge of the viewBox compared to the SVG is landscape, that is, wide (1.5px * 100 = 150px).
  • The SVG is 200px wide and the viewBox is 150px, which does not fit SVG.xMidDetermines that the viewBox is centered with respect to SVG. When the viewBox’s relatively short sides are vertical (height), yMind determines the vertical alignment of the viewBox.
  • It can be inferred that the origin of the coordinate system is shifted 25px + 0*1.5px to the right and 0px + 0*1.5px to the lower left corner of the SVG.

From this we can describe the preserveAspectRatio property abstractly:

The value of this attribute is in the format

graph LR
    xMin[Min]
    xMid[Mid]
    xMax[Max]
    yMin[Min]
    yMid[Mid]
    yMax[Max]
	x --> xMin
	x --> xMid
	x --> xMax
	xMin --> Y
	xMid --> Y
	xMax --> Y
	Y --> yMin
	Y --> yMid
	Y --> yMax
	yMin --> Space
	yMid --> Space
	yMax --> Space
	Space --> meet
	Space --> slice
  • If the viewBox aspect ratio is different from the ASPECT ratio of the SVG element

    • meet, will span the relatively long axis of the viewBox across the relatively short axis of the SVG. In other words, make sure the entire viewBox is in the SVG area. Such as example 4
    • slice, will stretch the relatively short axis of the viewBox across the SVG, and the relatively long axis of the viewBox will extend beyond the viewBox’s view area. Five such as cases,
    Example 5: xMidYMid slice
  • alignment

    • MinLeft/top alignment (example 6,8)
    • MidHorizontal/vertical centering (example 4,5)
    • MaxRight/bottom alignment (example 7,9)
Example 6: xMinYMid meet
Example 7: xMaxYMid meet
Example 8: xMidYMin slice
Example 9: xMidYMax slice

Width and height of an SVG element

From the above statement, we can see that the viewBox creates a coordinate system in which the numbers are ununited.the actual size is determined by the width and height of the SVG and its preserveAspectRatio. For the convenience of description, the latter is first defined as xMidYMid meet. The position and size of elements in SVG are proportional only to the width and height of the SVG element, so SVG is scalable. Example 10 shows three different sizes of SVG.

Example 10

What if the width and height of SVG are not specified?

The SVG specification makes it clear that there are two cases:

  1. If the viewBox doesn’t give it either, the default is equivalent to<svg width="300" height="150" viewBox="0 0 300 150"></svg>
  2. If the viewBox gives, the SVG width value isauto.autoThe value for a block-level element is its own width (border-box) equal to the parent element’s width (content-box). The specification does not explicitly state whether SVG elements are block-level or inline. We could give it a try.
<div>
    <div style={{ width: '400px' }}>
      <ViewBox viewBox='0 0 100 200' 	/>
    </div>
    <ViewBox viewBox='0 0 100 200' />
</div>
Copy the code

The result is shown below

Example 11
  • For the first SVG, if the parent element width dies, the SVG is also dead
  • For the second SVG, the parent element changes as the viewport changes, and the SVG width changes as well
  • In summary, an SVG value of auto behaves like a block element.

conclusion

  • SVG is a tool for drawing graphics using vectors (coordinate systems)
  • SVG throughviewBoxandpreserveAspectRatioProperty to create a coordinate system
  • viewBox
    • The first two values are used to determine the starting coordinates of the viewBox
    • The latter two values are used to determine the width and height of the viewBox
  • preserveAspectRatio
    • meet/sliceDetermine how the viewBox ADAPTS SVG. If it ismeetAdapt the short edge of SVG to ensure that the viewBox is in the SVG area, if sosliceThe other side of the viewBox will have an area that is out of the SVG range and truncated.
    • <x|Y><Min|Mid|Max>Determine how to align the direction in the viewBox that does not fit SVG.
    • After the fit and alignment are determined, the units and origin positions of the SVG coordinates can be determined.
    • Once the units and origin positions of SVG coordinates are determined, the positions and dimensions of all elements within the SVG can be determined.