Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play gif inside canvas in HTML5

Tags:

html

canvas

gif

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';
}
like image 543
Namratha Avatar asked Feb 14 '12 12:02

Namratha


2 Answers

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.

like image 101
rezoner Avatar answered Oct 24 '22 11:10

rezoner


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

like image 30
forresto Avatar answered Oct 24 '22 12:10

forresto