Skip to content Skip to sidebar Skip to footer

Can You Animate An Image On A Canvas

since I'm learning new to html and javascript, I was wondering if you can place an moving image side to side on a canvas? If so how can this be done please??? Here's what I've to d

Solution 1:

You can animate a spritesheet instead of a .gif.

The sequence is simple:

  1. Clear the canvas,
  2. Draw the next sprite in sequence and position it to advance across the canvas.
  3. Wait a while (perhaps in a requestAnimationFrame loop).
  4. Repeat #1.

Here's annotated code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// timing related vars
var nextTime=0;
var spriteCount=7;
var interval=700/spriteCount;
// sprite related vars
var sIndex=0;
var sw=60;
var sh=95;
var animationOn=true;

// current x,y position of sprite
var x=100;
var y=100;

// load the spritesheet
var ss=new Image();
ss.onload=start;
ss.src="http://i59.tinypic.com/jpkk6f.jpg";
function start(){

  // draw the first sprite
  ctx.drawImage(ss,sIndex*sw,0,sw,sh,x,y,sw,sh);

  // start the animation loop
  requestAnimationFrame(animate);

}

function animate(time){
  // wait for the specified interval before drawing anything
  if(time<nextTime || !animationOn){requestAnimationFrame(animate); return;}
  nextTime=time+interval;
  // draw the new sprite
  ctx.clearRect(0,0,cw,ch);
  ctx.drawImage(ss,sIndex*sw,0,sw,sh,x,y,sw,sh);
  // get the next sprite in sequence
  if(++sIndex>=spriteCount){sIndex=0;}
  // advance the sprite rightward
  x+=5;
  if(x>cw){x=-sw-10;}
  // request another animation loop
  requestAnimationFrame(animate);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Post a Comment for "Can You Animate An Image On A Canvas"