Frame by frame animation in HTML5 with canvas

大城市里の小女人 提交于 2019-11-28 22:08:22

Try this:

var imgNumber = 1;
var lastImgNumber = 4;

var ctx = canvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
  ctx.drawImage( img, 0, 0 );
};
var timer = setInterval( function(){
  if (imgNumber>lastImgNumber){
    clearInterval( timer );
  }else{
    img.src = "images/left_hnd_"+( imgNumber++ )+".png";
  }
}, 1000/15 ); //Draw at 15 frames per second

An alternative, if you only have 4 images, would be to create a single huge image with all four in a 'texture atlas', and then use setTimeout or setInterval to call drawImage() with different parameters to draw different subsets of the image to the canvas.

This worked for me as well! For some reason, it didn't work when I had used the OP's opening code: function draw(){

However when I used: window.onload = function draw() { the animation plays on the canvas. I'm also using about 150 PNG images with an Alpha channel so this is a great way to bring 'video' or create composites to the iPad/iPhone. I confirm that it does work on iPad iOS 4.3.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!