javascript canvas setTimeout console TypeError:不是函数

时间:2015-11-09 04:43:46

标签: javascript canvas settimeout

我正在尝试在单击按钮时执行“绘制”功能(按钮ID也是绘制)。单击按钮时,函数成功运行,但重复的迭代不会运行。因此我将问题缩小到了setTimeout。我得到以下消息“绘制不是一个函数”。这很令人困惑,因为它绝对是一个功能。任何帮助表示赞赏。感谢。

 var draw1 = document.getElementById('draw');
 draw1.addEventListener('click',draw);

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;

function draw(aaa,bbb){
      ctx.save();//save the cavas state if required
      ctx.clearRect(0,0,100,100)//clear canvas for redrawing
      ctx.fillStyle = 'rgba(0,200,0,1)';//style a green box
      ctx.fillRect (x, 20, 50, 50);//draw the rectangle
      ctx.restore();//restore the canvas state if saved
      x += 5;//increment the x position by some numeric value
      console.log(x);
      console.log(y);
      var loopTimer = setTimeout('draw(' + x +','+ 0 +')',200);
    }

1 个答案:

答案 0 :(得分:2)

不要使用字符串进行函数调用。这是一个非常糟糕的做法。

将其更改为匿名函数:

var loopTimer = setTimeout(function() {
    draw(x, 0);
}, 200);

只要您的xy是全局的并且您不使用参数,就可以从draw方法中删除它们,并将其称为更简单,无需关闭:

function draw(){
    ctx.save();//save the cavas state if required
    ctx.clearRect(0,0,100,100)//clear canvas for redrawing
    ctx.fillStyle = 'rgba(0,200,0,1)';//style a green box
    ctx.fillRect (x, 20, 50, 50);//draw the rectangle
    ctx.restore();//restore the canvas state if saved
    x += 5;//increment the x position by some numeric value
    console.log(x);
    console.log(y);
    var loopTimer = setTimeout(draw, 200);
}