How to play gif inside canvas in HTML5

27,968

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
27,968
Admin
Author by

Admin

Updated on January 05, 2021

Comments

  • Admin
    Admin over 3 years

    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';
    }