HTML5逐帧动画(多个图像)

时间:2015-09-07 05:29:39

标签: javascript html5 canvas

我一直在为此而失去理智。我花了3个小时尝试不同的方法,并在网上找到解决方案,我仍然没有修复它。 我有两个单独的图像(不是spritesheet),它们需要一个接一个地显示,作为一个动画,无限。这是我的最新代码:

var canvas, context, imageOne, imageTwo, animation;    

function init(){
  canvas = document.getElementById("canvas");
  context = canvas.getContext("2d");

  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  imageOne = new Image();
  imageTwo = new Image();

  imageOne.src = "catone.png";
  imageTwo.src = "cattwo.png";

  // Just to make sure both images are loaded
  setTimeout(function() { requestAnimationFrame(main);}, 3000);
}

function main(){

  animation = {

    clearCanvas: function(){
      context.clearRect(0, 0, canvas.width, canvas.height);
    },

    renderImageOne: function(){
      context.drawImage(imageOne, 100, 100);
    },

    renderImageTwo: function(){
      context.drawImage(imageTwo, 100, 100);
    }

  };

  animation.renderImageOne();

  // I also tried calling animation.clearCanvas();
  context.clearRect(0, 0, canvas.width, canvas.height);

  animation.renderImageTwo();

  // I put this here to confirm that the browser has entered the function, and that it hasn't stopped after animation.renderImageTwo();
  console.log("cats");
  requestAnimationFrame(main);
}

init();

但问题是只显示了一张图片,而且它没有移动。我无法在控制台中看到任何错误或警告。我还确定HTML和JavaScript连接正确,图像处于正确的路径。因此,在任何情况下,仅显示第一个函数中的图像。示例:animation.renderImageOne();显示catone,但如果我用animation.renderImageTwo()替换它;它显示了cattwo。

1 个答案:

答案 0 :(得分:2)

问题在于:

  animation.renderImageOne();

  // I also tried calling animation.clearCanvas();
  context.clearRect(0, 0, canvas.width, canvas.height);

  animation.renderImageTwo();

它是否正在绘制第一张图像,清除画布,然后绘制第二张图像,然后绘制到屏幕上。让你只看到第二张图片。您将需要一个替换值的变量,并使用它来确定您应该绘制哪个图片:

var canvas, context, imageOne, imageTwo, animation;   
var imageToDraw = "one";

然后:

function main() {

  ...

  if(imageToDraw == "one") {
      animation.renderImageOne();
      imageToDraw = "two";
  }
  else if(imageToDraw == "two") {
      animation.renderImageTwo();
      imageToDraw = "one";
  }

  ...
}

注意:您不需要在animation内定义main(),您可以将其移至全局范围。这样,每次拨打main()时,您都不会重新定义它。