只是試驗JS +畫布,我似乎碰壁了。 我的最小應用程序的「目標」是點擊畫布上的任意位置,按下繪製按鈕並在您點擊的地方繪製正方形。javascript類型問題:未捕獲TypeError:對象0沒有方法'繪製'
來自面向對象的背景......我(試過)使用面向對象,這在JS我沒有完全掌握。
但基本上我有一個自定義的方形物體
function Square(l, w, x, y) {
this.length = l;
this.width = w;
this.posx = x - l/2;
this.posy = y - w/2;
//test
//ctx.fillStyle = "rgb(20,0,0)";
//ctx.fillRect(this.posx,this.posy,this.length,this.width);
this.draw = function() {
ctx.fillStyle = "rgb(20,0,0)";
ctx.fillRect(this.posx,this.posy,this.length,this.width);
}
}
我在用戶每次點擊一次添加到一個數組... 這裏是當我點擊畫布上的事件處理程序。
function addTo(evt) {
pos = getMousePos(evt);
var sq = new Square(50, 50, pos.x, pos.y);
list.push(sq);
output.innerText = "("+sq.posx+","+sq.posy+")";
}
這裏是我在哪裏(嘗試)畫正方形。
function renderStack() {
//alert(list);
canvas.width = canvas.width;
for(var o in list) o.draw();
}
,這是錯誤:
Uncaught TypeError: Object 0 has no method 'draw'
,我收到了類似的錯誤嘗試訪問該變量爲對象。 看來,我將它們添加到列表中後,js忘記了它們是什麼類型? - 因爲當我打印數組時它充滿[Object object]的
謝謝。
偏離主題,但從構造函數中取出'draw'方法,並將它放在'prototype'上。 'Square.prototype.draw = func ...' – 2011-12-23 15:36:33
謝謝,JS新手,尤其是對象的任何好資源;我讀過一些相互矛盾的東西。 – 2011-12-23 15:53:58