cre*_*orn 0 javascript oop canvas
刚尝试使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
我每次用户点击时都会添加一个数组...这里是我点击画布时的事件处理程序.
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+")";
}
Run Code Online (Sandbox Code Playgroud)
这是我(尝试)绘制正方形的地方.
function renderStack() {
//alert(list);
canvas.width = canvas.width;
for(var o in list) o.draw();
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
Uncaught TypeError: Object 0 has no method 'draw'
Run Code Online (Sandbox Code Playgroud)
我试图访问该对象的变量时遇到类似的错误.似乎在我将它们添加到列表后,js会忘记它们是什么类型的? - 因为当我打印数组时,它充满了[Object object]
谢谢.
for ... in ...为您提供对象的键而不是其内容.
因此,在Array上,您将收到存储元素的索引和任何其他可枚举属性的名称.
相反,你应该使用:
for (var i = 0; i < list.length; ++i) {
list[i].draw();
}
Run Code Online (Sandbox Code Playgroud)