svg 是否在 viewbox 之外计算?

Does a svg compute outside of viewbox?

我有几个对象在 react 中移动到 svg 的视图框之外。为了优化,我想有条件地渲染它。所以外面的物体不会被渲染。但我问自己是否真的需要。 SVG 是否计算视图框外部的内容?

是的,浏览器会计算视口之外的所有内容以进行渲染。计算但不显示在视图框中。因此,该问题仅与渲染性能相关。如果包含很多小细节的非常大的 svg 文件的一部分位于 viewBox 之外,那么渲染将很困难。虽然这只会显示 SVG 的可见部分。

问题作者的评论:

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

正在计算视口的宽度

下面是一个包含两个 SVG 形状的示例。一张图在 svg 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>
<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>     

圆圈在 canvas 的 svg 之外,所以它不会在浏览器中呈现

这是矢量编辑器中的样子

为了使两个图形都在 svg 中canvas,您需要计算 viewBox 的参数。
为此,将两个形状放入组标记 <g> 并计算 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>

设置计算的 viewBox 属性

它是:viewBox="0 0 600 300"

现在: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>