【发布时间】:2016-10-19 14:13:07
【问题描述】:
我只是想不通为什么我的绘图函数是未定义的。它与原型有关。本质上,我希望创建的每个新对象都有自己的 x、y、dx 和 dy,这样我就可以使用对象创建多个弹跳球,并且我认为使用原型为每个对象创建方法将是一种有效的方式。
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);
}
});
错误:未捕获的引用错误:未定义绘制
【问题讨论】:
-
@mplungjan
bind返回一个函数,因此它可以很好地传递给 setInterval,但第一个参数似乎错误,因为它应该是this绑定上下文。 -
@mplungjan 怎么不绑定?
-
请发布完整的错误日志
-
@Karim 给你,也更新了帖子,Uncaught ReferenceError: draw is not defined.Ty :)
-
问题可能是
draw没有定义。
标签: javascript object prototype