![](/img/trans.png)
[英]Javascript: Uncaught TypeError: window.setTimeout(…) is not a function
[英]javascript canvas setTimeout console TypeError: is not a function
我試圖在單擊按鈕時執行函數“繪制”(按鈕 ID 也是繪制)。 單擊按鈕時,函數成功運行,但重復迭代不運行。 因此,我已將問題縮小到 setTimeout。 我收到以下消息“draw is not a function”。 這令人困惑,因為它絕對是一個函數。 任何幫助表示贊賞。 謝謝。
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);
}
不要使用字符串進行函數調用。 這是一個非常糟糕的做法。
將其更改為匿名函數:
var loopTimer = setTimeout(function() {
draw(x, 0);
}, 200);
只要你的x
和y
是全局的並且你不使用參數,你就可以從你的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.