如何在 canvas 上的按键上设置精灵动画?

How to animate sprites on keypress on canvas?

如何在按键时为角色设置动画?我更改了显示下一张图片的 sprite 位置,但我如何循环播放这两张图片,以便在按下键时可以显示播放器 运行。

我需要第一帧和第二帧。

关键事件:

if(keys[39]){
      //right arrow
      if (mario.velX < mario.speed){
        mario.velX++;

        if(!mario.jumping){
          //mario sprite position
          mario.frame = 0;
        }
      }
    }

绘制函数

this.frame = 0;

  var marioImg; //mario image

  var that = this;

  this.init = function() {
    marioSprite = new Image();
    marioSprite.src = 'images/mario-sprites.png';
  }

  this.draw = function(){
    that.sX = that.width * that.frame;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(marioSprite, that.sX, that.sY, that.width, that.height, that.x, that.y, that.width, that.height);
  }

将两张图片载入数组

var imageArray = []; // array to hold images
var img = new Image(); // create and load first image
img.src = "imageOne.png";
imageArray.push(img);  // put it in the array

img = new Image(); // same for image two
img.src = "imageTwo.png";
imageArray.push(img);

您将需要一些变量。一个控制每个图像显示多长时间,另一个控制显示哪个图像。您可以使用当前时间来保持它的美观和均匀。

var millsecondsPerImage = 100;  // each frame is 100 ms 1/10th of a second

var currentTime = new Date().valueOf(); // get the time in milliseconds

// Divide current time by how long to display for. Round down with floor
// then modulo the length of the image array
var imageToDraw = imageArray[Math.floor(currentTime / millsecondsPerImage) % imageArraylength];

// draw the current image image
ctx.drawImage(imageToDraw, posx, posy);

这将循环任意数量的图像,无论您在数组中放入多少图像。