我对如何使用,定义,更改和取消设置javascript对象感到困惑。
我的JavaScript对象是:
var Ship = function(){
return {
canvas: $('#area')[0],
canvas_width: this.canvas.width,
canvas_height: this.canvas.height,
context: this.canvas.getContext("2d"),
ship_image: new Image(),
ship_width: null,
ship_height: null,
ship_x: 0,
ship_y: 0,
init: function() {
this.ship_image.onload = function() {
this.ship_width = this.width;
this.ship_height = this.height;
this.ship_x = (this.canvas_width / 2) - (this.ship_width / 2);
this.ship_y = this.canvas_height - this.height;
this.draw(
this.ship_x,
this.ship_y
);
}
this.ship_image.src = "ship.gif";
},
draw: function(x, y) {
this.context.drawImage(
this.ship_image,
x,
y
);
}
}
}();
当我执行这段代码时;
$(function(){
Ship.init();
Controller.init();
});
我每次都会收到此错误。
Uncaught TypeError:无法读取第4行(ship.js)上未定义的属性'width'
未捕获的TypeError:第29行上的Ship不是函数(index.html / Ship.init())
我现在应该怎么办?
问题在于,this.canvas
它不指向canvas
对象的属性ship
,而是指向全局对象window
。您需要进行canvas_width
不同的初始化,例如在init函数中。并且与context
:
var Ship = function () {
return {
canvas: $('#area')[0],
ship_image: new Image(),
ship_width: null,
ship_height: null,
ship_x: 0,
ship_y: 0,
init: function () {
this.context = this.canvas.getContext("2d");
this.canvas_width = this.canvas.width;
this.canvas_height = this.canvas.height;
this.ship_image.onload = function () {
this.ship_width = this.ship_image.width;
this.ship_height = this.ship_image.height;
this.ship_x = (this.canvas_width / 2) - (this.ship_width / 2);
this.ship_y = this.canvas_height - this.ship_image.height;
this.draw(this.ship_x, this.ship_y);
}.bind(this);
this.ship_image.src = "ship.gif";
},
draw: function (x, y) {
this.context.drawImage(this.ship_image, x, y);
}
}
}();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句