如何在画布上的按键上激活精灵?

时间:2015-12-13 19:09:59

标签: javascript html canvas sprite

如何在按键上为角色设置动画?我更改了显示下一个图像的精灵位置,但是如何循环显示两个图像,以便在按下按键时显示播放器正在运行。

我需要第一帧和第二帧。

Keyevents:

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

1 个答案:

答案 0 :(得分:0)

将两个图像加载到数组

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

这将循环任意数量的图像,无论你放入阵列中的数量多少。