SVG Study Note
(Chinese) SVG Viewport and View Box written by Way Lau.
(Chinese) Understand viewport, viewVox, preserveAspectRatio in SVG by zhangxinxu.
viewport creates a new axis inside svg area. It provides a new scale inside svg.
It has two attribute:
height. These two attributes is defined as unit, such as
%, depends on css setting. The default unit is
<svg width="500" height="300"></svg> <!-- A svg area with width of 500 unit, height of 300 unit-->
viewbox is a way of scaling svg view-able space. it has four attributes:
height. Note a positive value in y-position meaning counting down from start point.
The use of
viewbox is to expand item to full svg area, following the scale defined in
viewbox. For example,
<svg width="500" height="300" viewbox="0 0 150 300"></svg> means define a area width a width of 150 and height of 300 from zero-point, then expand it to full svg (width 500 height 300). Everything inside viewbox will be also re-scaled.
A great demo (Chinese) created by zhangxinyu can be found here.
preserveAspectRatio has two attributes:
how viewBox align with viewport,
ratio of height and width.
The first attribute has two parts:
x alignment and
y alignment. Options are:
viewboxalign on left edge
viewboxalign on center of x-axis
viewboxalign on right edge
viewboxalign on top edge
viewboxalign on middle of y-axis
viewboxalign on bottom edge
So, a full option for first attribute is something like
The second attribute has following option:
viewbox following its ratio, even the graph is out of svg area.
<svg width="400" height="200" viewBox="0 0 200 300" preserveAspectRatio="xMinYMin meet" style="border:1px solid #cd0000;"> <rect x="10" y="10" width="300" height="300" fill="#cd0000"/> </svg>
Result from code above. Notice the rectangle is still in 2:3 ratio for width:height.
Keep current ratio, while expanding
viewbox till short slide of
viewport is filled (Even though the inner shape is smaller width/height than svg, the short side of svg is still be filled).
Result from code above. Note height is filled first, since it's the shorter side:
viewbox is hardly defined by its own width and height, without following any ratio.
Result from code above. :
preserveAspectRatio is market, following result should be seen:
Also see this demo created by zhangxinxu.