繁体   English   中英

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

[英]How to animate sprites on keypress on canvas?

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

我需要第一帧和第二帧。

关键事件:

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

将两个图像加载到and数组中

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM