Categories
React

Animation with the react-tweenful Library — SVG Animation

Spread the love

With the react-tweenful library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with the react-tweenful.

SVG Animation

We can add animations to SVGs with the SVG object.

For example, we can write:

import React from "react";
import { SVG, percentage, elastic } from "react-tweenful";

const circles = new Array(5).fill(0).map((_e, i) => ({
  loop: true,
  fill: `hsl(${(i + 1) * 20 - 20}, 70%, 70%)`,
  delay: ((i + 1) * 1500) / -10,
  duration: 1500,
  easing: elastic(2, 0.9),
  transform: {
    translate: "0 100px"
  },
  style: {
    transformOrigin: `${-200 + 120 * (i + 1)}px 250px`
  },
  animate: percentage({
    "0%": { translate: "0px 100px", scale: 1 },
    "50%": { translate: "0px -100px", scale: 0.3 },
    "100%": { translate: "0px 100px", scale: 1 }
  }),
  r: 35,
  cx: 100 * i + 50,
  cy: 250
}));

export default function App() {
  return (
    <div className="bouncing-balls">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        x="0px"
        y="0px"
        viewBox="0 0 1000 500"
      >
        {circles.map((circle, i) => (
          <SVG.circle key={i} {...circle}></SVG.circle>
        ))}
      </svg>
    </div>
  );
}

to add a bouncing ball effect.

The circles array has objects which are created with styles that we apply to create the bouncing ball effect.

fill has the fill color.

loop set to true means we repeat the animation forever.

delay has the animation delay.

duration has the duration of the animation.

easing has the easing of the animation.

transform is the CSS transform property.

style has more styles we apply.

animate lets us add styles applied at the given progress for the animation.

r , cx , and cy have the radius, and the x and y coordinates of the center of the circle respectively.

In the JSX, we create the svg component with the SVG.circle components inside it.

We apply all the animation styles by spreading the circle properties that we created earlier.

Now we should see the bouncing ball effect displayed.

Conclusion

We can animate SVGs easily with the react-tweenful library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *