Nargis
Nargis

Reputation: 769

Create multiple GIFs from the same source in P5.js

I am creating a game where I have to use same gif at multiple places. I used this method to create and display a gif.

But when I try to use it multiple times in different time interval. All the frames remain sync instead of starting from start next time: I modified above code to this one:

var open, frame, o1;

function preload() {
  load = loadImage("doorOpen.gif");
}

function setup() {
  createCanvas(0, 0);
  background(0);
}

function draw() {
  open = createImg("doorOpen.gif");
  open.position(0, 0);
  open.size(100,100);

  setTimeout(function(){
    o1 = createImg("doorOpen.gif")
    o1.position(0,150);
    o1.size(100,100);
  }, 1000);
}

What I want is that when I add second GIF, it plays from start. But instead of that; it starts from the position of first GIF.

Upvotes: 0

Views: 258

Answers (1)

Ethan Hermsey
Ethan Hermsey

Reputation: 940

Good news, it's possible.

You are creating new html elements with the gif as the image source. Your browser tries to be smart about it and trying to save on resources, loads the gif once and then displays it over and over.

You can trick the browser to think it's a different image by adding '?' and a random number to the url. It will still load the same image but it will be unique. I've shown how to do this below.

On another note; when calling createImg() in the draw function like you did above, it adds 2 image elements EVERY frame, and will result in thousands of images in the DOM and crash your browser. I moved it to the setup function.

var open, o1;

function setup() {

  createCanvas(0, 0);
  background(0);

  open = createImg("doorOpen.gif");
  open.position(0, 0);
  open.size(100, 100);

  setTimeout(function() {
    o1 = createImg("doorOpen.gif?" + random());
    o1.position(0, 150);
    o1.size(100, 100);
  }, 800);

}

Upvotes: 1

Related Questions