为什么这个html5画布动画不起作用?

时间:2013-02-18 21:40:25

标签: html5 animation canvas setinterval

所以我正在尝试在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);
 }

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题