Search code examples
javascriptanimationspritep5.js

How to assign a GIF to a sprite in JS with p5JS libraries?


I have a local GIF file, and I want to assign the output to a sprite.

enter image description here

I have the following libraries in use, if it matters at all :-

  • p5.js
  • p5.play.js
  • p5.dom.min.js
  • p5.sound.min.js

Also, I don't want to split the GIF into separate images.


Solution

  • If you are talking about p5.play sprites specifically you'll need to be more explicit with your question. However, generally speaking using animated gifs in p5.js is very straightforward. You can just load and draw them like any other image using the loadImage and image functions.

    let gif;
    
    function preload() {
      gif = loadImage('https://www.paulwheeler.us/files/EQ1QT.gif');
    }
    
    function setup() {
      createCanvas(windowWidth, windowHeight);
    }
    
    function draw() {
      background(255);
      image(gif, mouseX - 20, mouseY - 20, 40, 40);
    }
    <script src="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>