rendering-animate-svg

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Animate SVG Wrapper Instead of SVG Element

为SVG的外层容器添加动画,而非直接动画SVG元素

Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a
<div>
and animate the wrapper instead. Important for 8-bit components with pixel art icons and animations.
Incorrect (animating SVG directly - no hardware acceleration):
tsx
function PixelSpinner() {
  return (
    <svg
      className="animate-spin"
      viewBox="0 0 16 16"
    >
      <rect x="2" y="2" width="4" height="4" fill="currentColor" />
    </svg>
  )
}
Correct (animating wrapper div - hardware accelerated):
tsx
function PixelSpinner() {
  return (
    <div className="animate-spin">
      <svg
        viewBox="0 0 16 16"
        width="16"
        height="16"
      >
        <rect x="2" y="2" width="4" height="4" fill="currentColor" />
      </svg>
    </div>
  )
}
For 8-bit icon components with hover effects:
tsx
function RetroIcon({ icon: Icon, className }: RetroIconProps) {
  return (
    <div className={cn("transition-transform hover:scale-110", className)}>
      <Icon />
    </div>
  )
}
This applies to all CSS transforms and transitions (
transform
,
opacity
,
translate
,
scale
,
rotate
). The wrapper div allows browsers to use GPU acceleration for smoother animations, which is especially noticeable for retro pixel art animations.
许多浏览器对SVG元素的CSS3动画不支持硬件加速。将SVG包裹在
<div>
中,转而对包裹容器添加动画。这在带有像素艺术图标和动画的8位组件中尤为重要。
错误示例(直接为SVG添加动画 - 无硬件加速):
tsx
function PixelSpinner() {
  return (
    <svg
      className="animate-spin"
      viewBox="0 0 16 16"
    >
      <rect x="2" y="2" width="4" height="4" fill="currentColor" />
    </svg>
  )
}
正确示例(为外层div添加动画 - 硬件加速):
tsx
function PixelSpinner() {
  return (
    <div className="animate-spin">
      <svg
        viewBox="0 0 16 16"
        width="16"
        height="16"
      >
        <rect x="2" y="2" width="4" height="4" fill="currentColor" />
      </svg>
    </div>
  )
}
适用于带有悬停效果的8位图标组件:
tsx
function RetroIcon({ icon: Icon, className }: RetroIconProps) {
  return (
    <div className={cn("transition-transform hover:scale-110", className)}>
      <Icon />
    </div>
  )
}
这适用于所有CSS变换和过渡效果(
transform
opacity
translate
scale
rotate
)。外层div能让浏览器利用GPU加速实现更流畅的动画效果,这在复古像素艺术动画中表现得尤为明显。