reactjs - svg 是否在 viewbox 之外计算?

标签 reactjs svg

<分区>

我有几个对象在 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

计算视口(viewport)的宽度

下面是一个包含两个 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 之外,因此不会在浏览器中呈现

这是它在矢量编辑器中的样子

enter image description here

为了使两个图形都在 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/

相关文章:

svg - 组合 <use>-tags 或使用 <use>-tags 制作 <path>

javascript - 无限自动播放 slider 提前结束,并且不会无限循环

javascript - 使用 Redux Toolkit 异步 REST API 模式时如何捕获 HTTP 4xx 错误?

javascript - 如何用 jest 和 enzyme 模拟 React 组件方法

reactjs - 如何在图表中的 x 轴上显示自定义值?

python - 将 ReactJS 与 Jinja2 和 Webapp2 结合使用

html - 笔画动画,如何将另一条路径附加到出现的笔画?

java - iText 7 SVG 作为背景

javascript - 使用 SVG,将鼠标悬停在 X、Y 或 Z 上以使 X 和 Z 旋转

css - 造型 nvd3 图表