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

本文实例为大家分享了js通过循环多张图片实现动画展示的具体代码,供大家参考,具体内容如下

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

动画思路:

1.将图片资源放在数组里面

2.通过计时器来设定间隔时间

3.通过计数器来取相应的图片 

第一步:基本框架,鱼身体

<body>

<canvas id="canvas1" width="800" height="600"></canvas>

</body>

document.body.onload = game;

var can1,

ctx1,

canWidth,

canHeight,

lastTime = Date.now(),

deltaTime = 0,

body = new Image();

function game() {

init();

gameloop();

}

function init() {

can1 = document.getElementById("canvas1"); //fonr--fishes, UI, circles, dust

ctx1 = can1.getContext("2d");

canWidth = can1.width;

canHeight = can1.height;

body.src = './src/baby.png';

}

function bodyDraw(){

ctx1.drawImage( body, -body.width * 0.5, -body.height * 0.5);

}

function gameloop() {

requestAnimFrame(gameloop);

//时间帧间隔

var now = Date.now();

deltaTime = now - lastTime;

lastTime = now;

ctx1.clearRect(0, 0, canWidth, canHeight);

bodyDraw();

}

window.requestAnimFrame = (function() {

return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||

function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {

return window.setTimeout(callback, 1000 / 60);

};

})();

第二步:摇动尾巴

1.图片资源有8张,从tail0.png ~ tail7.png

2.尾巴是匀速的运动,间隔时间为固定值

var bTailTimer, //计时器

bTailCount, //计数器

babyTail = []; //图片数组

function init() {

//尾巴初始化

bTailTimer = 0; 8 bTailCount = 0; 9 for (var i = 0; i < 8; i++) {

babyTail[i] = new Image();

babyTail[i].src = './src/tail' + i +'.png';

}

}

function tailDraw(){

bTailTimer += deltaTime;

if(bTailTimer > 50){

bTailCount = (bTailCount + 1)% 8;

bTailTimer %= 50; //初始化计数器

}

ctx1.drawImage( babyTail[bTailCount], -babyTail[bTailCount].width * 0.5, -babyTail[bTailCount].height * 0.5);

}

function gameloop() {

ctx1.clearRect(0, 0, canWidth, canHeight);

bodyDraw();

tailDraw();

}

第三步:眨眼睛

1.图片资源有2张,从eye0.png ~ eye7.png

2.眼睛睁开时间不定时,闭上时间固定值

var bEyeTimer,

bEyeCount,

bEyeInterval, //时间间隔变量

babyEye = [];

function init() {

//眼睛初始化

bEyeTimer = 0;

bEyeCount = 0;

bEyeInterval = 1000; //间隔时间

for (var i = 0; i < 2; i++) {

babyEye[i] = new Image();

babyEye[i].src = './src/Eye' + i + '.png';

}

}

function eyeDraw() {

bEyeTimer += deltaTime;

if (bEyeTimer > bEyeInterval)

{

bEyeCount = (bEyeCount + 1)% 2;

bEyeTimer %= bEyeInterval;

if (bEyeCount == 0)

{

//眼睛睁开保持的时间随机

bEyeInterval = Math.random() * 1500 + 2000; //[2000,3500)

} else

{

//眼睛闭上保持时间固定为100ms

bEyeInterval = 100;

}

}

}

function gameloop() {

eyeDraw();

}

以上是 js通过循环多张图片实现动画效果 的全部内容, 来源链接: utcz.com/z/312248.html

回到顶部