我收到错误:
未捕获TypeError:rect.drawIt不是函数
我不明白为什么会出现这种错误?我的意思是我和这里一样: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();
};
&#13;
<canvas id="canv"></canvas>
&#13;
答案 0 :(得分:4)
首先定义Recta.prototype.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.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();
}
答案 1 :(得分:1)
在最后(在对象定义之后)编写以下代码
var context = document.getElementById("canv").getContext("2d");
for (var k = 0; k < 4; k++) {
var rect = new Recta();
rect.drawIt();
}