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:
- Clear the canvas,
- Draw the next sprite in sequence and position it to advance across the canvas.
- Wait a while (perhaps in a
requestAnimationFrame
loop). - 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 varsvar nextTime=0;
var spriteCount=7;
var interval=700/spriteCount;
// sprite related varsvar sIndex=0;
var sw=60;
var sh=95;
var animationOn=true;
// current x,y position of spritevar x=100;
var y=100;
// load the spritesheetvar ss=newImage();
ss.onload=start;
ss.src="http://i59.tinypic.com/jpkk6f.jpg";
functionstart(){
// draw the first sprite
ctx.drawImage(ss,sIndex*sw,0,sw,sh,x,y,sw,sh);
// start the animation looprequestAnimationFrame(animate);
}
functionanimate(time){
// wait for the specified interval before drawing anythingif(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 sequenceif(++sIndex>=spriteCount){sIndex=0;}
// advance the sprite rightward
x+=5;
if(x>cw){x=-sw-10;}
// request another animation looprequestAnimationFrame(animate);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvasid="canvas"width=300height=300></canvas>
Post a Comment for "Can You Animate An Image On A Canvas"