Just experimenting with JS + canvas and i seem to have hit a wall.
the “aim” of my minimal application is to click at any random place on the canvas, press the draw button and squares draw where you clicked.
coming from an OO background… i (tried) to use OO, which in js i dont fully have the grasp of.
but basically i have a custom Square object
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);
}
}
which i add to an array every time the user clicks…
here is the event handler for when i click on the canvas.
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+")";
}
and here is where i (attempt) to draw the squares.
function renderStack() {
//alert(list);
canvas.width = canvas.width;
for(var o in list) o.draw();
}
and this is the error:
Uncaught TypeError: Object 0 has no method 'draw'
i get a similar error trying to access the variables for that object.
It seems that after i add them to the list js forgets about what type they are? – because when i print the array it is full of [Object object]’s
thanks.
ois the index (or property) of array. You will access what’s stored at that index bylist[o].But for the arrays, it is better to use
forloop as shown by Alnitak thanfor-in.Update:
For-in is to be used when you need to loop through all the properties. Since array is an object it has indices and properties. So for-in will iterate through all the indices and properties. for-in is better for objects.
e.g.