首页  >  文章  >  web前端  >  为什么缩放 SVG 子元素会使其“从左上角飞入”以及如何修复它?

为什么缩放 SVG 子元素会使其“从左上角飞入”以及如何修复它?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-29 02:03:29720浏览

Why does scaling an SVG sub-element make it

SVG 子元素上的 CSS 变换源问题

问题:

尝试时要缩放 SVG 中的子元素,变换原点设置为整个 SVG 的 (0,0) 点,导致子元素在动画时看起来“从左上角飞入”。

解决方案:

要设置相对于正在动画的特定子元素的变换原点,请添加以下 CSS 规则:

<code class="css">transform-box: fill-box;</code>

此确保变换相对于子元素的边界框,允许其从中心缩放。

更新的示例:

<code class="css">@keyframes scaleBox {
  from {transform: scale(0);}
  to {transform: scale(1);}
}
#animated-box {
  transform-box: fill-box;
  animation: scaleBox 2s infinite;
}</code>
<code class="html"><svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" style="
        width: 195px;
    ">
    <defs>
    <style>.cls-1{fill:#7f7777;}.cls-2{fill:#fff;}
</style>
    </defs>
    <rect class="cls-1" x="0.5" y="0.5" width="99" height="99"></rect>
    <path d="M99,1V99H1V1H99m1-1H0V100H100V0Z"></path>
    <rect id="animated-box" class="cls-2" x="10.5" y="8.5" width="22" height="6"></rect>
</svg></code>

说明:

transform-b​​ox 属性确定元素的哪一部分用于计算变换原点。通过将其设置为 fill-box,可以使用子元素的边界框而不是父 SVG 的坐标空间来计算原点。

以上是为什么缩放 SVG 子元素会使其“从左上角飞入”以及如何修复它?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn