如何让SVG中animateTransform旋转linearGradient时居中?
问题
尝试用animateTransform实现线性渐变的居中旋转,但渐变无法居中,有问题的SVG代码如下:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="200px" height="200px" fill="none"> <rect width="100%" height="100%" fill="url(#grad)"/> <linearGradient id="grad"> <stop offset="0%" stop-color="red" /> <stop offset="100%" stop-color="yellow" /> <animateTransform attributeName="gradientTransform" type="rotate" from="0" to="360" dur="5s" repeatCount="indefinite" /> </linearGradient> </svg>
希望实现通过animate修改坐标达成的居中旋转效果,询问是否能用animateTransform实现该效果,目标效果的SVG代码如下:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="200px" height="200px" fill="none"> <rect width="100%" height="100%" fill="url(#grad)"/> <linearGradient id="grad"> <stop offset="0%" stop-color="red" /> <stop offset="100%" stop-color="yellow" /> <animate attributeName="x1" dur="2s" values="0%;0%;50%;100%;100%;100%;50%;0%;0%" repeatCount="indefinite"/> <animate attributeName="y1" dur="2s" values="50%;0%;0%;0%;50%;100%;100%;100%;50%" repeatCount="indefinite"/> <animate attributeName="x2" dur="2s" values="100%;100%;50%;0%;0%;0%;50%;100%;100%" repeatCount="indefinite"/> <animate attributeName="y2" dur="2s" values="50%;100%;100%;100%;50%;0%;0%;0%;50%" repeatCount="indefinite"/> </linearGradient> </svg>
解决方案
可以用animateTransform实现居中旋转效果,核心是指定旋转中心为SVG的中心点。
原代码问题在于:rotate变换默认以坐标原点(0,0)为旋转中心,所以渐变会绕左上角旋转,导致偏移。只需在from和to参数中添加旋转中心的坐标即可,SVG的viewBox是0 0 13 13,中心点坐标为6.5 6.5,也可以用百分比50% 50%(相对渐变的边界框,这里即整个SVG)。
修正后的代码如下:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="200px" height="200px" fill="none"> <rect width="100%" height="100%" fill="url(#grad)"/> <linearGradient id="grad"> <stop offset="0%" stop-color="red" /> <stop offset="100%" stop-color="yellow" /> <animateTransform attributeName="gradientTransform" type="rotate" from="0 6.5 6.5" to="360 6.5 6.5" dur="5s" repeatCount="indefinite" /> </linearGradient> </svg>
或者使用百分比形式的旋转中心,效果一致:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="200px" height="200px" fill="none"> <rect width="100%" height="100%" fill="url(#grad)"/> <linearGradient id="grad"> <stop offset="0%" stop-color="red" /> <stop offset="100%" stop-color="yellow" /> <animateTransform attributeName="gradientTransform" type="rotate" from="0 50% 50%" to="360 50% 50%" dur="5s" repeatCount="indefinite" /> </linearGradient> </svg>
这段代码会让渐变绕SVG中心持续旋转,和你用animate修改坐标的效果完全一致,且代码更简洁。
内容的提问来源于stack exchange,提问作者Sawy
相关产品推荐
相关产品推荐

