js通过循环多张图片实现动画效果
以小鱼摇尾巴和眨眼睛为例
动画思路:
1.将图片资源放在数组里面
2.通过计时器来设定间隔时间
3.通过计数器来取相应的图片
第一步:基本框架,鱼身体
<body> <canvas id="canvas1" width="800" height="600"></canvas> </body>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 })();
第二步:摇动尾巴
1.图片资源有8张,从tail0.png ~ tail7.png
2.尾巴是匀速的运动,间隔时间为固定值
1 var bTailTimer, //计时器 2 bTailCount, //计数器 3 babyTail = []; //图片数组 4 5 function init() { 6 //尾巴初始化 7 bTailTimer = 0; 8 bTailCount = 0; 9 for (var i = 0; i < 8; i++) { 10 babyTail[i] = new Image(); 11 babyTail[i].src = './src/tail' + i +'.png'; 12 } 13 } 14 15 function tailDraw(){ 16 bTailTimer += deltaTime; 17 if(bTailTimer > 50){ 18 bTailCount = (bTailCount + 1)% 8; 19 bTailTimer %= 50; //初始化计数器 20 } 21 ctx1.drawImage( babyTail[bTailCount], -babyTail[bTailCount].width * 0.5, -babyTail[bTailCount].height * 0.5); 22 } 23 24 function gameloop() { 25 ctx1.clearRect(0, 0, canWidth, canHeight); 26 27 bodyDraw(); 28 tailDraw(); 29 }
第二步:眨眼睛
1.图片资源有2张,从eye0.png ~ eye7.png
2.眼睛睁开时间不定时,闭上时间固定值
1 var bEyeTimer, 2 bEyeCount, 3 bEyeInterval, //时间间隔变量 4 babyEye = []; 5 6 function init() { 7 //眼睛初始化 8 bEyeTimer = 0; 9 bEyeCount = 0; 10 bEyeInterval = 1000; //间隔时间 11 for (var i = 0; i < 2; i++) { 12 babyEye[i] = new Image(); 13 babyEye[i].src = './src/Eye' + i + '.png'; 14 } 15 } 16 17 function eyeDraw() { 18 bEyeTimer += deltaTime; 19 if (bEyeTimer > bEyeInterval) 20 { 21 bEyeCount = (bEyeCount + 1)% 2; 22 bEyeTimer %= bEyeInterval; 23 24 if (bEyeCount == 0) 25 { 26 //眼睛睁开保持的时间随机 27 bEyeInterval = Math.random() * 1500 + 2000; //[2000,3500) 28 } else 29 { 30 //眼睛闭上保持时间固定为100ms 31 bEyeInterval = 100; 32 } 33 } 34 } 35 36 function gameloop() { 37 eyeDraw(); 38 }