首页 > 解决方案 > SVG 上的 CSS 变换原点始终 (0,0)

问题描述

我想让每个多边形/组出现一个动画。我希望它是 Y 轴上的旋转,旋转的原点是最左边顶点的 Y 轴(想象一张扑克牌在左边缘靠在桌子上后,从垂直到平面)。

但是,根据这个 Fiddle,变换的原点始终是 Y 轴,但始终 x = 0 作为旋转的原点,即使我使用最左边的顶点作为变换原点。

奖励:初始旋转后,我想等待 1 秒,然后以最右边顶点的 Y 轴为原点进行另一次旋转以使其消失(0 到 -90 度)。

.three {
    animation: spin 1s linear;
}

#three {
    transform-origin: 87px 153px;
    /*transform-origin: top left;*/
}

@keyframes spin {
    0% { 
        transform: rotateY(-90deg); 
    }  
    100% { 
        transform: rotateY(0deg); 
    } 
}
<svg width="1920" height="1080" xmlns="http://www.w3.org/2000/svg">
    <g class='three' fill="gray" stroke="black" stroke-width="1">
        <polygon id="three"  points="222,0 200,107 87,153" />
    </g>
</svg>

标签: cssanimationsvgtransformationcss-transforms

解决方案


应用于最外层<svg>元素的 3D 变换通常应该可以工作。

然而,将它们应用于 an 内的元素<svg>仍然有点不确定。

幸运的是,在这种情况下,您可以在不使用 3D 旋转的情况下重现您想要的内容。我们使用比例而不是旋转。我们使用一个缓动函数来模拟旋转中会发生什么。

#three {
    transform-origin: 87px 153px;
    animation: spin 1s linear;
    animation-timing-function: cubic-bezier(0.000, 0.550, 0.450, 1.000);
}

@keyframes spin {
    0% { 
        transform: scale(0, 1); 
    }  
    100% { 
        transform: scale(1, 1); 
    } 
}
<svg width="1920" height="1080" xmlns="http://www.w3.org/2000/svg">
    <g class='three' fill="gray" stroke="black" stroke-width="1">
        <polygon id="three"  points="222,0 200,107 87,153" />
    </g>
</svg>


推荐阅读