Does a svg compute outside of viewbox?

Viewed 152

I have several objects moving outside of the viewbox of a svg in react. For the sake of optimisation, I would like to conditionally render it. So the objects outside would not be rendered. But I'm asking myself if it's really needed. Does an SVG compute what is outside of a viewbox?

1 Answers

Yes, the browser computes everything outside the viewport for rendering. Calculates but does not display in the viewbox. Therefore, the question is relevant only in terms of rendering performance. If a part of a very large svg file with a lot of small details is outside the viewBox then rendering will be difficult. Although this will only show the visible part of the SVG.

comments of the author of the question:

I just do a 2.5d effect, so I have a prop for the pixels parcoured in the x axis. I know where is everything that way, and just need some calculation regarding the width of the viewbox

Calculating the width of the viewport

Below is an example with two SVG shapes. One figure is inside the svg viewBox, the second is outside

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="600" height="300" viewBox="0 0 600 300" style="border:1px solid" >  
  <g>
<rect x="20" y="50" width="200" height="200" rx="5%" fill="purple" />
           <!-- Circle cx = "800" outside viewBox = "0 0 600 300" -->
<circle cx="800" cy="150" r="140" fill="greenyellow" />
</g>
</svg>     

The circle is outside the svg of the canvas so it is not rendered in the browser

This is how it looks in the vector editor

enter image description here

In order for both figures to be inside the svg canvas, you need to calculate the parameters of the viewBox.
To do this, put both shapes in the group tag <g> and calculate the parameters of the viewBox

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="600" height="300" viewBox="0 0 600 300" style="border:1px solid" >  
         
  <g id="group">
<rect x="20" y="50" width="200" height="200" rx="5%" fill="purple" />
           <!-- Circle cx = "800" outside viewBox = "0 0 600 300" -->
<circle cx="800" cy="150" r="140" fill="greenyellow" />
</g>
</svg>     

<script>
 console.log(group.getBBox())
</script>

Setting the computed viewBox attributes

It was: viewBox="0 0 600 300"

Now: viewBox = "20 10 920 280"

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="600" height="300" viewBox="20 10 920 280" style="border:1px solid" >  
         
  <g id="group">
<rect x="20" y="50" width="200" height="200" rx="5%" fill="purple" />
           <!-- Circle cx = "800" inside viewBox = "0 0 920 280" -->
<circle cx="800" cy="150" r="140" fill="greenyellow" />
</g>
</svg>     

Related