1
因此,我正在嘗試使用javascript模塊模式和html5畫布,通過製作簡單的基於html5的遊戲,並遇到了我的第一個障礙。我在畫布上偵聽mousemove事件。如何從事件函數模塊模式調用函數
init: function() {
var gameCanvas = document.getElementById("gameCanvas");
gameCanvas.addEventListener("mousemove", this.redrawAvatar);
}
我在做的是讓我的頭像跟隨鼠標指針在畫布上的移動。
然後,問題是,我有我的模塊中的一些功能,我希望從redrawAvatar函數中調用,像這樣:
redrawAvatar: function (mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas"),
avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY},
enemyCoord = {x: 100, y: 100};
this.clear(gameCanvas);
this.drawAvatar(avatarCoord);
this.drawEnemy(enemyCoord);
if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) {
alert("Avatar died, collided with enemy");
}
}
雖然裏面redrawAvatar的這個對象是不是我的模塊了,但是是而不是事件(在這種情況下,畫布)
這裏的來源是我的模塊的精髓:
var MyGame = (function() {
var Game = {
draw: function (image, coord) {},
drawAvatar: function (coord) {},
clear: function (canvas) { canvas.width = canvas.width + 1 - 1;},
drawEnemy: function (xPos, yPos) {},
isCollision: function (a, b) {},
redrawAvatar: function (mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas"),
avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY},
enemyCoord = {x: 100, y: 100};
this.clear(gameCanvas);
this.drawAvatar(avatarCoord);
this.drawEnemy(enemyCoord);
if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) {
alert("Avatar died, collided with enemy");
}
},
init: function() {
var gameCanvas = document.getElementById("gameCanvas");
gameCanvas.addEventListener("mousemove", this.redrawAvatar);
}
};
(function() {
var that = Game;
that.init();
}());
}());
我怎麼給函數在我想要打給我的模塊中?
完美!並且對mdn也有很好的參考。 – Rythmic 2014-10-31 22:37:48