SVG (Scalable Vector Graphics) is an incredibly powerful format for rendering resolution-independent graphics on the web. When combined with CSS and JavaScript, you can create impressive, lightweight animations that work across all modern browsers. This article shows you how to build and animate SVG elements dynamically using code.
1. Why Use SVG for Web Animations?
SVGs are resolution-independent, stylable with CSS, animatable, and manipulable via JavaScript. They load fast and can be scaled or transformed without losing quality—making them ideal for icons, charts, loaders, and UI effects.
2. Creating a Simple SVG Element
Let’s start with a basic circle rendered via SVG:
<svg id="mySvg" width="200" height="200">
<circle id="myCircle" cx="100" cy="100" r="40" fill="#3498db" />
</svg>
This creates a blue circle in the center of a 200×200 canvas.
3. Adding CSS Animation
Use CSS keyframes to animate SVG properties like r
(radius) or fill
:
<style>
@keyframes pulse {
0%, 100% {
r: 40;
fill: #3498db;
}
50% {
r: 60;
fill: #9b59b6;
}
}
#myCircle {
animation: pulse 2s infinite ease-in-out;
}
</style>
4. JavaScript-Powered Interactivity
You can also update SVG elements dynamically using JavaScript:
<script>
const circle = document.getElementById('myCircle');
circle.addEventListener('mouseover', () => {
circle.setAttribute('fill', '#e74c3c');
circle.setAttribute('r', '50');
});
circle.addEventListener('mouseout', () => {
circle.setAttribute('fill', '#3498db');
circle.setAttribute('r', '40');
});
</script>
This adds interactivity to the SVG: hovering over the circle changes its color and size.
5. Chaining More Complex Animations
With JavaScript, you can animate multiple elements or chain effects using requestAnimationFrame()
. Here’s a bouncing ball simulation:
<svg id="animSvg" width="300" height="300">
<circle id="ball" cx="150" cy="50" r="20" fill="#2ecc71" />
</svg>
<script>
const ball = document.getElementById("ball");
let position = 50;
let velocity = 2;
let direction = 1;
function animate() {
if (position >= 280 || position <= 20) direction *= -1;
position += velocity * direction;
ball.setAttribute("cy", position);
requestAnimationFrame(animate);
}
animate();
</script>
6. When to Use SVG Over Canvas
Use SVG when you need DOM access, styling with CSS, or interactivity. Use Canvas when dealing with thousands of elements or complex real-time rendering like games or particle systems.
Conclusion
SVGs bring flexibility, performance, and interactivity to modern web design. By combining SVG with CSS animations and JavaScript logic, you can build highly engaging user interfaces and visual elements with clean, maintainable code.
If this post helped you, consider supporting me here: buymeacoffee.com/hexshift