以小鱼摇尾巴和眨眼睛为例

js通过循环多张图片实现动画效果

动画思路:

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 })();
View Code

相关文章:

  • 2022-12-23
  • 2021-11-01
  • 2021-09-23
  • 2022-12-23
  • 2021-12-08
  • 2021-10-07
  • 2021-11-11
  • 2021-12-22
猜你喜欢
  • 2021-11-24
  • 2022-01-20
  • 2022-12-23
  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案