How to Stop an Animated GIF from Looping with JavaScript?

Sometimes, we want to stop an animated gif from looping with JavaScript.

In this article, we’ll look at how to stop an animated gif from looping with JavaScript.

Stop an Animated GIF from Looping with JavaScript

To stop an animated gif from looping with JavaScript, we can copy the animated GIF content to a canvas element.

Then we hide the original img element with the animated GIF when the animation is over.

For instance, we write:

<canvas style='width: 300px; height: 100px'></canvas>

<img src="https://i.stack.imgur.com/PUSIu.gif">

to add the canvas and the img element.

Then we write:

const canvas = document.querySelector('canvas')
const {
  width,
  height
} = canvas
const img = document.querySelector('img')

setTimeout(() => {
  canvas.getContext('2d').drawImage(img, 0, 0, width, height);
  img.style.visibility = 'hidden'
}, 10000);

to select the canvas with document.querySelector.

Then we get the width and height of the canvas.

Next, we select the img element with document.querySelector.

And then we call setTimeout with a callback that gets the canvas context and calls the drawImage method to draw the content of the img element into the canvas.

The first argument is the img element.

The 2nd and 3rd arguments are the x and y coordinates of the top left corner.

And the last 2 arguments are the width and height.

Finally, we set the visibility CSS property of the img element to 'hidden' to hide it.

And we do that after 10 seconds as specified by the 2nd argument of setTimeout.

Conclusion

To stop an animated gif from looping with JavaScript, we can copy the animated GIF content to a canvas element.

Then we hide the original img element with the animated GIF when the animation is over.