Frame by frame animation in HTML5 with canvas

前端 未结 2 472
深忆病人
深忆病人 2020-12-15 02:09

I have a flash animation I am trying to convert to HTML5. Now I have taken out all the images. For example in the hand animation, I have taken images of all hand images. I h

2条回答
  •  無奈伤痛
    2020-12-15 02:26

    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.

提交回复
热议问题