SVG Animation Guide
SVG Animation Guide
SVG (Scalable Vector Graphics) can not only be used to draw vector graphics but also to create lightweight, high-quality animations. This article will introduce how to create SVG animations and demonstrate a fan example with controllable rotation speed.
Why Choose SVG Animation?
- Vector Nature: No matter how much you zoom in, the image remains sharp.
- Small File Size: Compared to GIFs or videos, SVG is usually smaller.
- Interactive: Animation properties can be controlled via CSS and JavaScript (Vue/React).
- Good Performance: Modern browsers have optimized SVG rendering.
SVG Animation Implementation Methods
1. CSS Animation (@keyframes)
This is the simplest and most commonly used method. You can apply CSS animations to SVG elements just like regular DOM elements.
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.fan-blade {
animation: spin 1s linear infinite;
transform-origin: center; /* Ensure rotation around the center */
}2. SVG Native Animation (<animate>)
SVG internally supports SMIL (Synchronized Multimedia Integration Language) animation tags, such as <animate> and <animateTransform>.
<rect x="10" y="10" width="100" height="100">
<animate attributeName="x" from="10" to="50" duration="2s" repeatCount="indefinite" />
</rect>3. JavaScript / Libraries (GSAP, Anime.js)
For complex animation sequences or scenarios requiring fine control, using JavaScript animation libraries is a better choice.
Practical Example: Controllable Fan
Below is an example combining Vue and SVG. We define an SVG graphic of a fan and use Vue's data binding to control the CSS animation-duration property, thereby achieving speed control.
Effect Demo
Code Implementation
Vue Component (SvgFan.vue):
<template>
<div class="fan-container">
<!-- Bind animationDuration style -->
<div class="fan-wrapper" :style="{ animationDuration: speed + 's' }">
<svg viewBox="0 0 100 100" width="200" height="200">
<!-- Fan blades -->
<g fill="#4CAF50">
<path d="M50 50 Q30 10 50 10 Q70 10 50 50" transform="rotate(0 50 50)" />
<path d="M50 50 Q90 30 90 50 Q90 70 50 50" transform="rotate(0 50 50)" />
<path d="M50 50 Q70 90 50 90 Q30 90 50 50" transform="rotate(0 50 50)" />
<path d="M50 50 Q10 70 10 50 Q10 30 50 50" transform="rotate(0 50 50)" />
</g>
<circle cx="50" cy="50" r="5" fill="#FFC107" />
</svg>
</div>
<div class="controls">
<input type="range" min="0.1" max="2" step="0.1" v-model.number="speed" />
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const speed = ref(0.5) // Animation duration, smaller is faster
</script>
<style scoped>
.fan-wrapper {
animation: spin linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>Summary
By combining SVG's vector advantages with Vue's reactive data capabilities, we can easily create web animations that are both beautiful and interactive. I hope this simple fan example inspires you!