Canvas 随机精灵的context.clearRect和drawImage?

Canvas 随机精灵的context.clearRect和drawImage?,canvas,html5-canvas,sprite,Canvas,Html5 Canvas,Sprite,随机猫头鹰出现在我的游戏中,与1个猫头鹰图像一起使用: owl.x = 54 + (Math.random() * (canvas.width - 64)); //from var reset function owl.y = 54 + (Math.random() * (canvas.height - 64)); 如何使用context.clearRect和drawImage的随机坐标从多个图像精灵表渲染owl精灵 var owl = { x: 0, y:

随机猫头鹰出现在我的游戏中,与1个猫头鹰图像一起使用:

 owl.x = 54 + (Math.random() * (canvas.width - 64)); //from var reset function
        owl.y = 54 + (Math.random() * (canvas.height - 64));
如何使用context.clearRect和drawImage的随机坐标从多个图像精灵表渲染owl精灵

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);

下面是一段带注释的代码,它可以播放精灵扑动的小鸟,还可以在画布上移动精灵

演示:

一次做两个动画的关键是保持两个定时器

每50毫秒,活门将切换到精灵表上的下一个图像

// 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
);