0
這裏奇怪的問題是小提琴與類中的對象(約翰Resig的簡單的傳承)
這一個工程
這一個沒有
對不起我包含了太多的代碼,只是想盡可能接近地進行測試。
第二個是使用一個對象來保存x和y值。第一個不是。
這可能是一個函數綁定問題,但我不完全確定。
我有這樣的代碼:
(function createClouds() {
var Cloud = Class.extend({
size: 0,
alpha: 0,
x: 0,
y: 0,
pos: {
x: 0,
y: 0
},
init: function (x, y, size, alpha) {
this.x = x;
this.y = y;
this.size = size;
this.alpha = alpha;
console.log(this.x) // this prints a random number. all good
},
update: function (time) {
},
draw: function (ctx) {
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')';
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.size, this.size);
ctx.closePath();
ctx.fill();
}
});
sg.Cloud = Cloud;
})();
然後我基本上創建與畫布上隨意點此對象。
for (var i = 0; i < 20; i++) {
var x = sg.util.getRandomInt(0, sg.currentGame.width);
var y = sg.util.getRandomInt(0, sg.currentGame.height - 260);
var size = sg.util.getRandomInt(20, 200);
var alpha = sg.util.getRandomNumber(.1, .6);
sg.createEntity(new sg.Cloud(x, y, size, alpha));
}
sg.createEntity將此實體添加到數組;
然後我調用一個方法。
for (var i = 0; i < sg.entities.length; i++) {
sg.entities[i].draw(this.context);
}
繪製所有實體。
上述工作正常。我得到隨機點。
如果我改變這個。
(function createClouds() {
var Cloud = Class.extend({
size: 0,
alpha: 0,
x: 0,
y: 0,
pos: {
x: 0,
y: 0
},
init: function (x, y, size, alpha) {
this.pos.x = x;
this.pos.y = y;
this.size = size;
this.alpha = alpha;
console.log(this.pos.x) //this prints a random number;
console.log(this.pos) //inspecting this object shows same points.
},
update: function (time) {
},
draw: function (ctx) {
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')';
ctx.beginPath();
ctx.fillRect(this.pos.x, this.pos.y, this.size, this.size);
ctx.closePath();
ctx.fill();
}
});
sg.Cloud = Cloud;
})();