1

I'm trying to add an animated gif to an html5 canvas object. The problem is that once added it doesn't play and stays on the first frame. I've tested the HTML5 document in Chrome and Firefox and the same issue occurs. I have opened the gif in Chrome and Firefox to ensure it is running its animation and it does run it fine, just not in an HTML5 canvas object...

Here is the code:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src="enemy1.gif";
</script>
</body>
</html>

Any help is much appreciated.

thed0ctor
  • 1,350
  • 4
  • 17
  • 34

1 Answers1

2

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.

Credit: https://stackoverflow.com/a/9278770/283863

What does a spritesheet looks like? It looks like this:
enter image description here

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 1
    This link helped me accomplish this and I figured it was worth [noting](http://atomicrobotdesign.com/blog/web-development/how-to-use-sprite-sheets-with-html5-canvas/) Very simple approach. Also to convert an animated gif to a spritesheet I used the [free program](http://www.bottomap.com/Software/A4B/A4B.html). I'm on Ubuntu and it worked perfectly fine in wine. – thed0ctor Apr 15 '12 at 16:27