我只是不明白为什么我的绘图函数未定义。这和原型(prototype)有关系。本质上,我希望创建的每个新对象都有自己的 x、y、dx 和 dy,以便我可以使用对象创建多个弹跳球,并且我认为使用原型(prototype)为每个对象创建方法将是一种有效的方法。
document.addEventListener("DOMContentLoaded", function(event){
var canvas,
context,
altezza,
larghezza,
x = 100,
y = 100,
raggio = 25,
dx = 5,
dy = 5,
immagine,
ballTest;
window.onload = init;
//Assegniamo a canvas l'elemento HTML canvas
canvas = document.getElementById("campo");
//Assegniamo a context un oggetto che contiene tutti i metodi per disegnare
context = canvas.getContext("2d");
//Assegniamo a "dy" una velocità iniziale di 0.1 che verrà incrementato nel tempo
dy = 0.1;
//Assegniamo a immagine l'immagine della sfera
immagine = new Image;
immagine.src = "tBall.png";
//Assegniamo alle variabli altezza e larghezza le dimensioni del campo
larghezza = window.screen.availWidth - 40;
altezza = window.screen.availHeight - 120;
function Entity(x, y, raggio){
this.x = x;
this.y = y;
this.raggio = raggio;
draw();
}
Entity.prototype.draw = function(){
context.clearRect(0, 0, context.canvas.width, context.canvas,length);
context.drawImage(immagine, x, y, raggio, raggio);
};
//MIGHT NEED TO PUT THIS.X AND THIS.Y
Entity.prototype.move = function(dx, dy){
if(this.x < -10 || this.x > larghezza - 20){
dx *= -1;
}
if(this.y < 20 || this.y > altezza - 40){
dy *= -1;
}
this.x += dx;
this.y += dy;
};
function init(){
//Assegniamo a canvas l'elemento HTML canvas
canvas = document.getElementById("campo");
//Assegniamo a context un oggetto che contiene tutti i metodi per disegnare
context = canvas.getContext("2d");
//Settiamo le dimensioni del campo di canvas
context.canvas.width = larghezza;
context.canvas.height = altezza;
//Inizializziamo l'entità
ballTest = new Entity(100, 100, 25);
setInterval(ballTest.move.bind(dx, dy), 10);
}
});
错误: Uncaught ReferenceError :未定义绘制
最佳答案
draw
函数位于 Entity
的原型(prototype)中,因此在 Entity
类中,您必须以 this.draw 的形式访问它()
.
function Entity(x, y, raggio){
this.x = x;
this.y = y;
this.raggio = raggio;
this.draw();
}
关于JavaScript - 原型(prototype)方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40133878/