Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the viewBox property when HTML5 uses SVG images

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to use the viewBox attribute when HTML5 uses SVG images, I believe most people don't know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's go to know it together.

The viewBox property is used to specify the origin and size of the coordinate system of the user's SVG image. Everything drawn in SVG is done relative to this coordinate system. Because the SVG canvas is infinitely extended in all directions, you can even draw graphics outside the boundaries of the coordinate system; but the graphics positioned relative to the SVG window can also be controlled by the position of the user coordinate system.

The viewBox property uses four parameters to specify the location of the origin of the coordinate system and its size: x y width height. Initially, this coordinate system is equivalent to the initialized window coordinate system (determined by the width and height of the SVG image), and its origin is at (0,0)-- the upper-left corner of the SVG.

You can adjust the position of the origin by changing the values of the x and y parameters. You can change the size of the coordinate system by changing the values of width and height. Just use the viewBox property to help you extend or crop the SVG canvas. Read along with the example.

Important: in this article, I will not change the default behavior (scale and position) of viewBox in the SVG window. Because, according to the default behavior of the property, the contents of the viewBox are fully contained in the window as much as possible, and then placed in the center. However, using the preserveAspectratio property gives you the freedom to change the size and position of the viewBox, but in this article, this is not a required technique, so we won't cover it in depth here.

Use viewBox to crop SVG, even if you use the viewBox attribute to make the SVG of Art Direction

A while ago, one of my clients asked for his website's SVG avatar to be set to different sizes according to different screen sizes, so that only a small part of it is visible on a small screen, a larger part can be seen on a medium screen size, and then the full content can be seen on a large screen. The first thought that came to mind at the time was that his request was to use the viewBox attribute to crop the SVG image and then display part of the image he wanted to see depending on the screen size.

By changing the size and origin position of the SVG coordinate system, we can crop the SVG and display the part of the content we want to display in the window.

Let's see how to do it.

Suppose we have this complete SVG image below, and then we want to cut it to the size of a small screen. This image is a free-to-use house vector designed by Freepik and licensed under the Creative Commons Attribution 3.0 Unported agreement. For simplicity, let's assume that the image is only to be tailored to the content displayed on the small and medium-sized screen, as well as the complete content displayed on the large screen, as shown below.

The picture on the left is the complete picture that we are going to crop using the viewBox property, and the picture on the right is the area we want to display on the small screen.

Now, crop the SVG by changing the value of the viewBox property. There are some things to consider, which we will talk about later. But first, we need to change the coordinate system so that it matches the contents of the imaginary rectangle in the image above. By adjusting the origin of the system and the values of width and height, we can change its initial parameter value of 00800800.

But how do we know the new coordinates and dimensions? The point is not to go through a lot of repetitive experiments and mistakes.

There are several ways. Because we are already in the graphical editor (my example uses AI), we can use the editor's panel to get the location and size of the element.

In addition to representing what I want to display on the small screen, another reason I draw the rectangle is that we can get the location and size of the rectangle and use them as the value of viewBox. Using AI's transform panel (shown below), we get the values we need. By selecting the rectangle and clicking the transform link in the upper right corner, we get the panel shown in the following figure, including the x, y, width and height values we need.

The transform panel in this AI can be used to obtain the values of the position and size of the selected rectangle.

You may have noticed that the above values are not integers, so we need to modify them manually. Based on the above information, we changed the value of viewBox to 0200512512.

Because the aspect ratio of the new viewBox is the same as that of the SVG window (both square), the content in the viewBox will be expanded, and only the selected areas will be displayed in the window. After changing the value of viewBox, the result is as follows:

Newly cut SVG. Only the location where we specify to use the viewBox property is visible in the window. The blue border represents the window of the SVG.

At this point, there is a problem that needs to be solved:

If the aspect ratio of the cropped area (that is, viewBox)! = the aspect ratio of the SVG window?

In this case, there will be a significant overflow. By obvious overflow, I don't mean an extension beyond the boundaries of the SVG window, but an overflow defined by viewBox relative to the new user's coordinate system. The following picture is illustrated accordingly.

If the aspect ratio of the viewBox is different from the aspect ratio of the window, the content in the SVG will overflow the user coordinate system, which may be the result.

The black border represents the new user coordinate system, and the blue border is the SVG window.

The black border in the image above is the area defined by viewBox. According to the default behavior of viewBox in the window, it is centered and enlarged as much as possible to ensure that its content is contained in the window (blue border) as much as possible.

Because the SVG canvas is conceptually infinitely extended in all directions, you can draw graphics outside the boundaries of the user's coordinate system, and the content will directly overflow and move, as shown in the image above.

If you change the aspect ratio of SVG windows (SVG's width and height) to adapt them to the aspect ratio of viewBox, you won't see the overflow, because viewBox zooms to fit the window, as in the previous example.

However, in some cases, you may not be able or want to change the aspect ratio of SVG at all. For example, if you use SVG sprite as a set of images to display pictures on a page. In most cases, the image has a fixed aspect ratio-and you don't want to change the size of the image, just to fit the contents of a small image in it. Or maybe you embed an icon system and want all icons to be the same size at the same time.

To cut out the extra stuff (for example, some of the other icons on the sprite are displayed in the window), you can use it to cut out the extra parts. The cropping path can be an element that covers the entire viewBox area, and then applies that element to the root SVG.

However, there is one more thing to remember: make sure that the x and y properties are consistent with the viewBox, unless the rect will be relatively positioned at the origin of the original / initialized system, then what SVG will eventually be cut is uncertain.

CSS Code copies content to the clipboard

Of course, cutting the extra parts means that you are still using different aspect ratios, or you still need to solve the extra gaps on both sides of the content. If the SVG is a continuous scene, like our previous example, it won't be necessary because you also need to adjust the aspect ratio of the window. If SVG is a set of icons and you only use it once in a different window, this may not be a problem.

One important thing to keep in mind here is that the aspect ratio of the viewBox is best consistent with the aspect ratio of the window; in addition, you need to set a fixed to avoid any uncertain extra white space in the SVG.

Therefore, viewBox can be used to tailor the SVG and show only a portion of the SVG as needed. But how does it apply to instances?

Art Directing SVG in responsive Design

There is nothing to add to this section, except for the code of the actual process. So, suppose you have the SVG shown above and want to use it as an avatar, for example, you only want to display the cut part of the content on a small and medium-sized screen, and then display the full avatar on the big screen.

By changing the width and height values of the SVG window, we can use CSS. But to change the value of viewBox, we currently need to use JavaScript.

Not all SVG properties can be used equally with the CSS property; only a set of properties that have the same effect as the CSS property can be set in CSS. You can see an overview of this set of SVG properties that can be used as CSS properties in this table. In SVG2, many attributes (such as x, y, cx, cy, r, and so on) can be added to this list; but these are properties that we can use now.

To show different parts of SVG, you need to change the value of viewBox based on different media queries. You can use Modernizr, find the media query criteria, and then change the value of viewBox in JavaScript. Examples are as follows:

CSS Code copies content to the clipboard

/ / get the reference to root

Var svgRoot =.; / / depends on how you embed and reference SVG

/ / define the parameter values of viewBox

Var vbValue = '0200 512 512'

/ / use Modernizr's media query retrieval to change the value of viewBox

If (Modernizr.mq ('(max-width: 700px)')) {

SvgRoot.setAttribute ('viewBox', vbValue)

}

/ / other dimensions

This works, but wouldn't it be better if we could use CSS to do it?

Use the viewBox property of CSS to crop the SVG

Disclaimer: at the time of writing, there is no CSSviewBox attribute. This is just an example of why this property is useful and how I imagine it to be used.

Ideally, we could use it like this:

CSS Code copies content to the clipboard

@ media screen and (max-width: 700px) {

Svg {

ViewBox: 0 200 512 512

}

}

/ * etc. * /

These styles will be put into (or out of) the SVG, and then the SVG will adjust its viewBox value according to the size of the window. Make it the case of a page window (inline), or a window determined by the size of any other element that references SVG (which gives us some pretty much the same element query).

However, this is currently not possible because there is no viewBox attribute in CSS.

Not long ago, I asked an editor of the SVG specification on this question, and he said that I could make suggestions to SVGWG based on actual usage and examples. After some discussion on Twitter, I realized that there was a similar SVGWG proposal thread a few years ago. The original proposal still exists today, so I hope that it can be advanced through some practical examples and can be implemented in the near future. If you also want to see the viewBox attribute in CSS, please help achieve this goal and promote the forwarding and comments of this proposal.

Things to keep in mind when using viewBox to complete SVG Art-Direction

While working on my client's project, I spent less than a minute art-direct the avatar according to the requirements of the other person. However, this eventually leads to three separate SVG, rather than the same SVG and different viewBox on different screen sizes.

The reason why we chose the three SVG is that the size of the full SVG is too large, reaching the size of more than 100kb on the mobile side. The original SVG was about 200kb, and I could compress the file to nearly half its size by optimizing SVG, but the picture was still too large for mobile devices, so in the end we could only use three images of different sizes. When art-directing SVG, you need to keep in mind: performance issues. If your SVG is too big, don't use viewBox to art-direct.

Now, if you choose to use three different SVG images, there are many possible ways to do this-depending on how you embed SVG, and on what you want to accomplish and what you don't want to accomplish.

Using elements to complete different SVG images is the ideal way. It not only provides us with different SVG to choose from according to the browser, but also does not need to use JavaScript, but also allows us to provide a variety of optimized downgraded images for browsers that do not support it (IE8 and below). It is very useful for using SVG, you can read all the contents of SVG fallback in this article.

But as mentioned earlier, if you want an animated or interactive SVG, it's not the best choice. It's like using

Embedded SVG,SVG cannot be added with styles and animations unless styles and animations are defined in a file, SVG cannot add scripts (for security reasons), nor can there be any interaction (CSS or JS)-for example, hover, there will be no interaction.

So, I always say: SVG gives us a lot of options to get almost everything done; you need to make a tradeoff, prioritize, and sometimes even compromise, and make the best choice based on that. But for performance, never compromise is conducive to development!

Before we finish, because we mentioned the problem of using the viewBox attribute to resize the SVG canvas, let's take a look at another example, which we can use to save us some time and effort when dealing with SVG.

Extend the SVG canvas with viewBox

Just as the viewBox property can be used to scale SVG, it can also be used to extend the SVG canvas.

A few weeks ago I created a tool that can generate SVG round menus. I have created several examples to demonstrate how to use JavaScript to make the generated menu move. Demo uses elements to embed into the application page. Defines the boundaries of the SVG window, and anything outside these boundaries is overflowed and hidden by default.

It is important to note that "beyond the boundary" refers to the content in SVG, which is still on the infinite SVG canvas, but exceeds the infinite rectangle defined by the window.

Translator's note: for the contents of SVG canvas and windows, you can read the relevant articles on w3cplus.

To create a menu, the size of the SVG is just enough to include the menu, but not any larger. Avoid any extra white space around the menu.

I applied a bounce animation to a menu as an example of menu animation. This bounce effect "lengthens" the menu items and causes the menu items to be cut out separately (that is, overflow) when they bounce.

At first, because the SVG window is defined by elements, the window is the same size as the menu itself, and the bouncing effect on the menu items causes them to overflow when they bounce.

These lovely bounce animations are applied to projects that use the bounce time function to zoom in from 0 to 100% (that is, the project is initially invisible, reduced), and the effect is that if the project bounces to more than 100%, then shrink it back to 100%. This effect can cause the project to overflow when the bounce exceeds the SVG boundary.

The following illustration shows the effect of zooming a menu item when zooming in beyond the boundary (gray border), where it is used to embed the zoom menu item.

The diagram above shows the effect when the menu item is zoomed in to overflow the SVG window boundary. The gray border represents the border (that is, the element) of the SVG window.

Setting overflow: visible doesn't solve the problem either, because it's actually similar. What we need to do is to expand the SVG canvas created in the window so that the scaled item has enough "bounce" space without exceeding its boundary. We can use the viewBox attribute to do this.

To extend the SVG canvas, simply increase its size. Therefore, we are using the size of 700 x 500px instead of the original size of the 500 x 250 SVG menu. This also increases the height of the canvas in the window by 100px, while the width of the canvas in the window increases the 200px. I determine these values based on the amount of space that these menu items need to enlarge in the bounce effect. Depending on your SVG and what you want to accomplish, these values are not required to be consistent.

Now, to make sure that the menu is placed in the center of the window, we need to move the position of the coordinate system to the negative direction of 100px (that is, up and left). Applying this movement to the origin of the coordinate system is the same as applying a translation transformation to the menu in the system. The result is that the menu remains centered in the window.

In this figure, the blue border represents the SVG window boundary (that is, the element), and the gray border represents the initial size of the user's coordinate system. Blue numbers and arrows indicate an extension of the coordinate system in the window.

While extending the size of the user's coordinate system, you also increase the area of the canvas visible in the window. The result is that the content of the canvas will look a little smaller-depending on how much you enlarge the canvas. But for menus, this result is acceptable.

The following screenshot shows the result of extending the SVG canvas, as well as the menu animation within the SVG boundary.

Once the SVG canvas is expanded, the menu item has enough room to zoom and will no longer be cut because of the overflow when applying the bounce effect.

Extend the SVG canvas by changing the four parameter values of the viewBox property, so that all problems and menu items being cut can be solved. ViewBox is really great.

The above is all the content of the article "how to use the viewBox property when HTML5 uses SVG images". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report