首页 > 解决方案 > 使用此代码,我将如何在 JavaScript 中为精灵设置动画以在屏幕上闪烁 2 种不同颜色?或者更确切地说,我将如何解决它?

问题描述

我一直在尝试从精灵表中为标题屏幕设置动画。我已经加载了精灵表,但我似乎无法弄清楚为什么动画没有发生。我有一个不需要参数即可运行的更新函数:

function update(){
     menu.update
}

let frames = 0我的代码开头也有。我的问题是在绘制动画或其他内容时。它从动画中绘制第 0 帧,但不绘制第 1 帧。我曾尝试将动画师放在“if”语句下,但经过几次尝试后,我无法让它停止询问参数和/或表达式。(我尝试了一些箭头函数,但我不习惯使用它们,所以我不知道我所做的是对还是错。)

const menu = {
    animation : [
        {sX: 27, sY: 295},
        {sX: 27, sY: 399},
    ],
    x : cvs.width/2 - 118/2,
    y : 100,
    w : 118,
    h : 84,

    frame : 0,


     // Animator
     update : function(){
         // Incrementation % incrementation period (speed)
        this.frame += frames%5 == 0 ? 1 : 0;
        // Iteration of animation--draws 0 then 1 then 0....       
        this.frame = this.frame%this.animation.lenghth;

    },



    draw : function(){
        let animCounter = this.animation[this.frame];

        if(status.current == status.Start){

            ctx.drawImage(sprite, animCounter.sX, animCounter.sY, this.w, this.h, this.x, this.y, this.w, this.h);
        }
    },

   
}

我很确定问题出在“if”语句中,我可以让它与这个精灵表上的另一个精灵一起工作;它没有“if”语句,但除了源位置等之外的所有其他内容都是相同的。

标签: javascriptanimationmodulo

解决方案


这可能是由于一个简单的错字:

this.frame = this.frame%this.animation.lenghth;

应该读:

this.frame = this.frame%this.animation.length; // removed the "h"

这是一个交替河马的演示:-)

var sprite = document.getElementById('source');
var width = 600,
  height = 600,
  cvs = document.getElementsByTagName('canvas')[0],
  ctx = cvs.getContext('2d');
cvs.width = width;
cvs.height = height;

const menu = {
  animation: [{
      sX: 27,
      sY: 295
    },
    {
      sX: 27,
      sY: 399
    },
  ],
  x: cvs.width / 2 - 118 / 2,
  y: 100,
  w: 118,
  h: 84,

  frame: 0,
  frames: 0,

  // Animator
  update: function() {
    // Incrementation % incrementation period (speed)
    this.frame += this.frames % 5 == 0 ? 1 : 0;
    // Iteration of animation--draws 0 then 1 then 0....       
    this.frame = this.frame % this.animation.length;

        this.draw();
    window.setTimeout(function() {
      menu.update();
    }, 300);
  },

  draw: function() {
    let animCounter = this.animation[this.frame];
    //if (status.current == status.Start) {

      ctx.drawImage(sprite, animCounter.sX, animCounter.sY);
    //}
  }

}
menu.update();
<canvas></canvas>
<img id="source"
       src="https://mdn.mozillademos.org/files/5397/rhino.jpg"
       width="300" height="227" style="display:none;">


推荐阅读