以小鱼摇尾巴和眨眼睛为例
动画思路:
1.将图片资源放在数组里面
2.通过计时器来设定间隔时间
3.通过计数器来取相应的图片
第一步:基本框架,鱼身体
<body> <canvas id="canvas1" width="800" height="600"></canvas> </body>
1 document.body.onload = game; 2 3 var can1, 4 ctx1, 5 canWidth, 6 canHeight, 7 lastTime = Date.now(), 8 deltaTime = 0, 9 body = new Image(); 10 11 12 13 function game() { 14 init(); 15 gameloop(); 16 } 17 18 function init() { 19 can1 = document.getElementById("canvas1"); //fonr--fishes, UI, circles, dust 20 ctx1 = can1.getContext("2d"); 21 canWidth = can1.width; 22 canHeight = can1.height; 23 24 body.src = './src/baby.png'; 25 } 26 27 function bodyDraw(){ 28 ctx1.drawImage( body, -body.width * 0.5, -body.height * 0.5); 29 } 30 31 function gameloop() { 32 requestAnimFrame(gameloop); 33 34 //时间帧间隔 35 var now = Date.now(); 36 deltaTime = now - lastTime; 37 lastTime = now; 38 39 ctx1.clearRect(0, 0, canWidth, canHeight); 40 41 bodyDraw(); 42 } 43 44 45 46 window.requestAnimFrame = (function() { 47 return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || 48 function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) { 49 return window.setTimeout(callback, 1000 / 60); 50 }; 51 })();