5

I want to play animated GIF file inside a HTML Canvas. I have used the code below but it is not working.

What is wrong with the code?

var drawingCanvas = document.getElementById('myDrawingCanvas');
if(drawingCanvas.getContext) 
{
    var context = drawingCanvas.getContext('2d');
    var imgObj = new Image();

    imgObj.onload = function () 
    {       
        context.drawImage(imgObj, 0, 0, 1024, 600);
    }
    imgObj.src='HTML Images/Spell Bee/images/mainscreen.gif';
}
svet
  • 11,078
  • 1
  • 15
  • 26
Namratha
  • 111
  • 2
  • 2
  • 4

3 Answers3

7

You cannot as canvas doesn't provide any methods to deal with animated gifs. You should split gif into single frames then create a spritesheet and animate it copying current frame.

rezoner
  • 1,907
  • 13
  • 16
4

You can actually decode the GIF with JavaScript and write the frames to canvas. Check http://slbkbs.org/jsgif/

forresto
  • 12,078
  • 7
  • 45
  • 64
  • 3
    Update : the most relevant is to use the fork from buzzfeed : https://github.com/buzzfeed/libgif-js. They fork the project @forresto quoted, and added some basic functions. – Ser Dec 19 '15 at 15:31
1

I found an article that answers your question. Basically, when you add an animated gif to a canvas element it displays the exact state the image is at when it's included. So, as rezoner says, you need to create a spritesheet and animate it using javascript.

Alex Morales
  • 1,166
  • 9
  • 13