<分区>
我有几个对象在 react 中移动到 svg 的 View 框之外。为了优化,我想有条件地渲染它。所以外面的物体不会被渲染。但我问自己是否真的需要。 SVG 会计算 View 框之外的内容吗?
<分区>
我有几个对象在 react 中移动到 svg 的 View 框之外。为了优化,我想有条件地渲染它。所以外面的物体不会被渲染。但我问自己是否真的需要。 SVG 会计算 View 框之外的内容吗?
最佳答案
是的,浏览器会计算视口(viewport)之外的所有内容以进行渲染。计算但不显示在 View 框中。因此,该问题仅与渲染性能相关。如果包含很多小细节的非常大的 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>
关于reactjs - svg 是否在 viewbox 之外计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70028803/