【发布时间】:2011-12-23 15:23:31
【问题描述】:
只是在尝试 JS + canvas,我似乎碰壁了。 我的最小应用程序的“目标”是单击画布上的任何随机位置,按下绘图按钮并在您单击的位置绘制正方形。
来自 OO 背景...我(尝试)使用 OO,在 js 中我没有完全掌握。
但基本上我有一个自定义 Square 对象
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... -
谢谢,JS新手,特别是对象的任何好资源;我读过一些相互矛盾的东西。
标签: javascript oop canvas