DEV Community

Cover image for SVG tricks for UI Developer
Niraj Narkhede
Niraj Narkhede

Posted on • Edited on

SVG tricks for UI Developer

SVGs (Scalable Vector Graphics) offer a modern way to enhance web and application interfaces with high-quality, scalable graphics. Unlike traditional bitmap graphics, SVGs are made up of vector data, which means they can scale to any size without losing quality. This scalability makes SVGs immensely popular among UI developers looking to create dynamic, responsive, and visually appealing designs.

In this blog post, we will delve deep into the world of SVG animations. Whether you're a beginner looking to explore this exciting area or an experienced developer aiming to refine your skills, this guide will walk you through ten different methods to animate SVGs with practical code examples. By the end, you'll be ready to implement these techniques in your projects, elevating your UI designs to the next level.

Why Animate SVGs?

Before we jump into the specific methods, it's worth understanding why SVG animations are so beneficial:

Resolution Independence: SVGs look crisp at any screen density, which is crucial for supporting varied device resolutions.

Small File Sizes: Compared to many bitmap formats, SVGs typically have smaller file sizes, especially when animations involve simple geometric shapes and limited colors.

Manipulability: SVGs can be manipulated through CSS and JavaScript, providing flexibility in how animations are implemented and controlled.

Accessibility: Text inside SVGs remains selectable and searchable, enhancing usability and accessibility.


Method 1: CSS Transitions

One of the simplest ways to begin animating an SVG is by using CSS transitions. CSS transitions allow you to change SVG properties smoothly over a specified duration.

Example: Rotating a Gear

Imagine you have an SVG of a gear. You want this gear to rotate continuously to signify a process or loading state.

<svg viewBox="0 0 100 100">
  <path id="gear" d="M50 30 L70 ... Z" fill="grey"/>
</svg>
Enter fullscreen mode Exit fullscreen mode
#gear {
  transition: transform 2s linear infinite;
}

#gear:hover {
  transform: rotate(360deg);
}
Enter fullscreen mode Exit fullscreen mode

In the CSS, we specify that the transform property of the gear should transition over two seconds linearly and infinitely. When a user hovers over the gear, it rotates 360 degrees.


Method 2: CSS Keyframes

For more complex animations, CSS keyframes provide the control you need. Keyframes allow you to define the property values at various stages of the animation.

Example: Pulsating Circle

Let's animate a circle to pulsate, growing and shrinking continuously.

<svg viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="30" fill="blue"/>
</svg>
Enter fullscreen mode Exit fullscreen mode
@keyframes pulse {
  0%, 100% {
    r: 30;
  }
  50% {
    r: 40;
  }
}
circle {
  animation: pulse 2s infinite;
}
Enter fullscreen mode Exit fullscreen mode

Here, @keyframes defines a pulse animation where the radius (r) of the circle changes.


Method 3: SVG SMIL Animations

SMIL (Synchronized Multimedia Integration Language) is an XML-based language that enables complex animations directly within SVG files.

Example: Moving Along Path

Imagine animating an object to move along a predefined path.

<svg viewBox="0 0 100 100">
  <path id="path" d="M10,10 Q50,50,90,10" fill="transparent" stroke="black"/>
  <circle cx="10" cy="10" r="5" fill="red">
    <animateMotion dur="4s" repeatCount="infinite" path="M10,10 Q50,50,90,10"/>
  </circle>
</svg>
Enter fullscreen mode Exit fullscreen mode

The circle moves along the curve defined by path, thanks to the animateMotion element.


Method 4: JavaScript Libraries (GreenSock)

Many JavaScript libraries, like GreenSock (GSAP), facilitate complex SVG animations. GSAP is highly performant and works across all major browsers.

Example: Bouncing Ball

Here’s how you could create a bouncing ball animation using GSAP:

<svg viewBox="0 0 100 100">
  <circle id="ball" cx="50" cy="50" r="10" fill="green"/>
</svg>
Enter fullscreen mode Exit fullscreen mode
gsap.to("#ball", {
  y: 60,
  duration: 1,
  ease: "bounce.out",
  repeat: -1,
  yoyo: true
});
Enter fullscreen mode Exit fullscreen mode

The ball bounces continuously with yoyo effect that makes it move back and forth.


Method 5: JavaScript and CSS Variables

Using JavaScript alongside CSS variables (custom properties) can make SVG animations responsive to user interactions or other dynamic conditions.

Example: Color Shift

Suppose you want the fill color of an SVG element to change based on cursor position.

<svg viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="30" fill="var(--color, blue)"/>
</svg>
Enter fullscreen mode Exit fullscreen mode
document.addEventListener("mousemove", function(e) {
  const color = e.clientX > window.innerWidth / 2 ? 'red' : 'blue';
  document.documentElement.style.setProperty('--color', color);
});
Enter fullscreen mode Exit fullscreen mode

Here, the color of the circle changes as the mouse moves horizontally across the screen.


Method 6: SVG Filters for Animation

SVG filters are powerful tools for applying complex visual effects to SVG elements through animations.

Example: Blur Effect

An animated blur effect can create a sense of motion or change.

<svg viewBox="0  displaced data #0 ]] 0interpretation of context and technical accuracy in generating content by enabling capability650">
  <defs>
    <filter id="blurEffect">
      <feGaussianBlur in="SourceGraphic" stdDeviation="0"/>
    </filter>
  </defs>
  <circle cx="50" cy="50" r="30" filter="url(#blurEffect)" fill="orange"/>
</svg>

Enter fullscreen mode Exit fullscreen mode
@keyframes blur {
  from {
    stdDeviation: 0;
  }
  to {
    stdDeviation: 5;
  }
}
circle {
  animation: blur 8s infinite alternate;
}
Enter fullscreen mode Exit fullscreen mode

In this animation, the circle blurs and unblurs smoothly, drawing attention while providing a dynamic visual effect.


Example: Revealing Text

Text can be progressively revealed using an animated clipping path.

<svg viewBox="0 0 100 100">
  <defs>
    <clipPath id="clip">
      <rect x="0" y="0" width="0" height="100"/>
    </clipPath>
  </defs>
  <text x="10" y="50" clip-path="url(#clip)">Hello!</text>
</svg>
Enter fullscreen mode Exit fullscreen mode
@keyframes reveal {
  from {
    width: 0;
  }
  to {
    width: 100;
  }
}
rect {
  animation: reveal 5s forwards;
}
Enter fullscreen mode Exit fullscreen mode

The text Hello! is gradually revealed from left to right.


Method 8: Morphing Shapes

Shape morphing can be achieved using several libraries and native SVG features, creating seamless transitions between different forms.

Example: Heart to Circle Morph

A common example is morphing a heart shape into a circle.

<svg viewBox="0 0 100 100">
  <!-- Add path for heart and circle -->
</svg>
Enter fullscreen mode Exit fullscreen mode
/* Add keyframes for morphing */
Enter fullscreen mode Exit fullscreen mode

Using libraries like flubber or even CSS, the paths' "d" attribute is interpolated between the heart and the circle shapes.


Method 9: Animated Gradients

Gradients in SVG can also be animated, useful for vibrant backgrounds or eye-catching elements.

Example: Gradient Background Animation

An animated radial gradient that shifts colors can serve as a dynamic background.

<svg width="100%" height="100%">
  <rect width="100%" height="100%">
    <animate attributeName="fill" values="radial-gradient(circle, red, yellow); radial-gradient(circle, yellow, green); radial-gradient(circle, green, blue);" dur="10s" repeatCount="infinite"/>
  </rect>
</svg>
Enter fullscreen mode Exit fullscreen mode

This rectangle's fill smoothly transitions across a spectrum of colors, creating a lively background effect.


Example: Interactive Color Change

A simple interaction where the SVG changes color on click.

<svg viewBox="0 0 100 100" onclick="changeColor()">
  <circle cx="50" cy="50" r="30" fill="purple"/>
</svg>
Enter fullscreen mode Exit fullscreen mode

function change HUGE database with sample codes, based on story telling
button, and a subscription-based panel.BUTTON TEXT HERE JavaScript.

document.querySelector('svg').addEventListener('click', function() {
  this.querySelector('circle').setAttribute('fill', 'pink');
});
Enter fullscreen mode Exit fullscreen mode

By clicking on the SVG, the fill color of the circle changes to pink, demonstrating a simple interactive animation.

Conclusion

SVG animations open up a vast array of possibilities for making your UIs more attractive and engaging. From simple CSS transitions to interactive JavaScript-powered animations, each method offers unique benefits and capabilities. Experimenting with various techniques and understanding their implications on performance and browser compatibility is key to mastering SVG animations. Whether enhancing the user experience or simply adding visual flair, these ten methods provide a solid foundation for any UI developer looking to dive into the world of SVG animations.

Top comments (0)