【问题标题】:How to animate sprites on keypress on canvas?如何在画布上的按键上为精灵设置动画?
【发布时间】:2015-12-14 04:36:52
【问题描述】:

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

我需要第一帧和第二帧。

关键事件:

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

【问题讨论】:

    标签: javascript html canvas sprite


    【解决方案1】:

    将两张图片加载到数组中

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

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

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 2011-02-10
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2013-09-08
      • 2020-04-29
      相关资源
      最近更新 更多