【问题标题】:why isn't this html5 canvas animation working?为什么这个 html5 画布动画不起作用?
【发布时间】:2013-02-03 10:36:24
【问题描述】:

所以我正在尝试加深对 Canvas 中动画的理解,但由于某种原因,这段代码无法正常工作。黄色矩形出现,但位置没有迭代。这个脚本在我的 html 代码中被引用为<script src = "images/drawing.js"></script>。这是drawing.js:

 var x = 400;
 var y = 300;

 function init() {

     var canvas = document.getElementById("canvas");
     var context = canvas.getContext("2d");
     canvas.width = 800;
     canvas.height = 600;

     context.fillStyle = "black";
     context.fillRect(x,y,150,150);
     setInterval(animateBox(context), 30);

 }



 function animateBox(context) {

     context.clearRect(0,0,context.canvas.width,context.canvas.height);
     x += 5;
     context.fillStyle = "yellow";
     context.fillRect(x,y,150,150);
 }

【问题讨论】:

  • “不工作”不是一个很好的描述...
  • 你说得对,我会解决的。

标签: html animation canvas setinterval


【解决方案1】:

setInterval(animateBox(context), 30);改为

setInterval(function(){
    animateBox(context)
}, 30);

我认为这就是问题所在。问题有点模糊。确保您也调用了 init() 函数(尽管您可能是)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-02
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2019-03-09
    • 2014-10-04
    相关资源
    最近更新 更多