Reputation: 1704
I get the error:
Uncaught TypeError: rect.drawIt is not a function
I don't understand why this error happens? I mean i am doing the same as here: http://www.w3schools.com/js/js_object_prototypes.asp
var context = document.getElementById("canv").getContext("2d");
for (var k = 0; k < 4; k++) {
var rect = new Recta();
rect.drawIt();
}
function Recta() {
this.x1 = Math.floor(Math.random() * context.canvas.width);
this.y1 = Math.floor(Math.random() * context.canvas.height);
this.x2 = Math.floor(Math.random() * context.canvas.width);
this.y2 = Math.floor(Math.random() * context.canvas.height);
this.x3 = Math.floor(Math.random() * context.canvas.width);
this.y3 = Math.floor(Math.random() * context.canvas.height);
this.x4 = Math.floor(Math.random() * context.canvas.width);
this.y4 = Math.floor(Math.random() * context.canvas.height);
};
Recta.drawIt = function () {
context.moveTo(this.x1, this.y1);
context.lineTo(this.x2, this.y2);
context.stroke();
context.moveTo(this.x2, this.y2);
context.lineTo(this.x3, this.y3);
context.stroke();
context.moveTo(this.x3, this.y3);
context.lineTo(this.x4, this.y4);
context.stroke();
context.moveTo(this.x4, this.y4);
context.lineTo(this.x1, this.y1);
context.stroke();
};
<canvas id="canv"></canvas>
Upvotes: 3
Views: 144
Reputation: 8488
First define the Recta.prototype.drawIt
then use it.
function Recta() {
this.x1 = Math.floor(Math.random() * context.canvas.width);
this.y1 = Math.floor(Math.random() * context.canvas.height);
this.x2 = Math.floor(Math.random() * context.canvas.width);
this.y2 = Math.floor(Math.random() * context.canvas.height);
this.x3 = Math.floor(Math.random() * context.canvas.width);
this.y3 = Math.floor(Math.random() * context.canvas.height);
this.x4 = Math.floor(Math.random() * context.canvas.width);
this.y4 = Math.floor(Math.random() * context.canvas.height);
};
Recta.prototype.drawIt = function () {
context.moveTo(this.x1, this.y1);
context.lineTo(this.x2, this.y2);
context.stroke();
context.moveTo(this.x2, this.y2);
context.lineTo(this.x3, this.y3);
context.stroke();
context.moveTo(this.x3, this.y3);
context.lineTo(this.x4, this.y4);
context.stroke();
context.moveTo(this.x4, this.y4);
context.lineTo(this.x1, this.y1);
context.stroke();
};
var context = document.getElementById("canv").getContext("2d");
for (var k = 0; k < 4; k++) {
var rect = new Recta();
rect.drawIt();
}
Upvotes: 4
Reputation: 4621
Write the below code at the last (after definition of the object)
var context = document.getElementById("canv").getContext("2d");
for (var k = 0; k < 4; k++) {
var rect = new Recta();
rect.drawIt();
}
Upvotes: 1