Loop gif n number of times?

Hi everyone! I’m trying to figure out how to loop a gif a specific number of times, after which it stops at the first frame.

I know that I can stop and pause a gif with play() (reference | p5.js) and manipulate the speed of the gif with delay() (I can’t include a third link in this post but I can post the link in a response if it is relevant).

My main goal is to modify the input example (examples | p5.js) so that after a user clicks the submit button the greet() function loops the gif the number of times that corresponds to the number that the user entered into the field. I think I have most of it figured out, but I can’t quite figure out how to deal with the gif looping.

Any ideas or pointers would be most welcome.

thank you!

Hi,

In the documentation, you also have those methods :

But with those, it’s going to be tedious to get the number of repetitions since the current number of frame loops constantly.

p5.Image.prototype.getCurrentFrame = function() {
  if (this.gifProperties) {
    const props = this.gifProperties;
    return props.displayIndex % props.numFrames;
  }
};

I looked at the source code and I found that you can access the actual number of frames played since the beginning :

gif.gifProperties.displayIndex

So then it’s easy :

let nRepetitions;

function setup() {
  // The number of repetitions of the gif
  nRepetitions = getUserInput();

  gif.play();
}

function draw() {
  // Stop the gif if reached the number of repetitions
  if (gif.gifProperties.displayIndex % gif.numFrames() >= nRepetitions) {
    gif.stop();
  }
}

Amazing! Thank you so much!

1 Like