随机猫头鹰出现在我的游戏中,它与1个猫头鹰图像一起使用:
owl.x = 54 + (Math.random() * (canvas.width - 64)); //from var reset function
owl.y = 54 + (Math.random() * (canvas.height - 64));
如何使用context.clearRect和drawImage的随机坐标从几个图像(精灵表)渲染猫头鹰精灵?
var owl = {
x: 0,
y: 0,
width: 54,
height: 54,
frames: 2,
currentFrame: 0,
};
//from render function:
if (owlReady) {
context.clearRect(0, 0, width, height);
context.drawImage(owlImage, owl.x, owl.y * currentFrame, width, height, width, height);
if (currentFrame == frames) {
currentFrame = 0;
}
else {
currentFrame++;
}
}
setInterval(render, 550);
答案 0 :(得分:0)
这是一个带注释的代码,可以播放精灵(拍打鸟)并在画布上移动精灵。
演示:http://jsfiddle.net/m1erickson/beudK/
一次做2个动画(翻动和移动)的关键是保持2个定时器。
每隔50ms,襟翼就会变成spritesheet上的下一个图像。
// calculate the elapsed times since the last flap
var elapsedFlap=currentTime-lastFlap;
// if 50ms have elapsed, advance to the next image in this sprite
if(elapsedFlap>50){
// advance to next sprite on the spritesheet (flap)
bird.currentFrame++;
// clamp bird.currentFrame between 0-3 (0,1,2,3)
// (because there are 4 images that make up the whole bird sprite)
if(bird.currentFrame>bird.frames-1){
bird.currentFrame=0;
}
// reset the flap timer
lastFlap=time;
}
精灵在画布上从左向右移动,每100毫秒移动
// calculate the elapsed times since the last move
var elapsedMove=time-lastMove;
// if 100ms have elapsed, move the bird across the canvas
if(elapsedMove>100){
bird.x+=3;
lastMove=time;
}
在计算了当前精灵图像和画布上精灵的位置之后,然后使用.drawImage从精灵表中剪切所需的精灵,并在画布上的所需位置绘制它:
// clear the whole canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw the current part of the bird sprite at the current bird.x
ctx.drawImage(spritesheet,
sx,sy,bird.width,bird.height, // clip the desired sprite off the spritesheet
bird.x,bird.y,bird.width,bird.height // draw to the desired position on the canvas
);