Auto-resize SVG inside AngularJS directive based on container element

不问归期 提交于 2019-12-03 20:30:19

This behavior can be achieved using the viewBox and preserveAspectRatio attributes of the <svg> tag.

First, set the viewBox attribute to a normalized bounding box for your SVG image. Your entire drawing should be scaled to fit inside this view box. For example,

viewBox="0 0 100 100"

will set up a coordinate system with the origin at (0, 0) and having the dimensions 100 units x 100 units.

Next, set the resizing behavior using the preserveAspectRatio attribute.

The first part of the value determines the alignment of the SVG with respect to the parent element. This includes left/right/center horizontal alignment and top/bottom/middle vertical alignment. For example,

preserveAspectRatio="xMidYMid ..."

will align the SVG centrally in its container.

The second part of the value determines how the SVG fills the container. For example,

preserveAspectRatio="... meet"

will scale the SVG such that it just fits within the container without cropping.

So the complete example becomes:

<svg viewBox="0 0 64 64" preserveAspectRatio="xMidYMid meet">
    ...
</svg>

Because the image scales automatically with the container, there is no need to recalculate the positions of the content elements. It is handled automatically by the SVG tag.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!