DEV Community

Cover image for useSpriteAnimation() like how Facebook does it using React Hooks
Kenneth Lum
Kenneth Lum

Posted on • Edited on

2 2

useSpriteAnimation() like how Facebook does it using React Hooks

When we post animated images to Facebook, it is displayed as Sprite Animation. We can also try using React Hooks to do it.

The image may look like this:

Sprite image

To do animation, we could write a custom React Hook useBackgroundShift():

function useBackgroundShift(size, xacross, yacross, xymax) {
  const [shift, setShift] = useState({ dx: 0, dy: 0 });

  useEffect(() => {
    let intervalID;

    if (size.width !== null && size.height !== null) {
      intervalID = setInterval(() => {
        setShift(({ dx, dy }) => {
          if (dx + dy * yacross + 1 >= xymax) {
            dx = 0;
            dy = 0;
          } else if (++dx >= xacross) {
            dx = 0;
            if (++dy >= yacross) {
              dy = 0;
            }
          }
          return { dx, dy };
        });
      }, 132);
    }

    return () => intervalID && clearInterval(intervalID);
  }, [size.width, size.height, xacross, yacross, xymax]);

  if (size.width === null || size.height === null) return {};

  return {
    backgroundPosition: `-${(shift.dx * size.width) / xacross}px -${
      (shift.dy * size.height) / yacross
    }px`,
    backgroundRepeat: "no-repeat"
  };
}
Enter fullscreen mode Exit fullscreen mode

I also added the ability to animate from frame 1 to frame N, just to see how it works. It is not yet perfect as I only did it as an experiment. Some might be hard coded numbers for the moment, but that's the basic idea of a custom React Hooks to do Sprite Animation.

Demo: https://codesandbox.io/s/beautiful-leaf-o9hew?file=/src/App.js

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay