早先在當耐特的 Demo 裡看過一款飛機射擊遊戲,順手把圖片與音效資源扒下來,隨著玩心重寫了一版。純粹娛樂性質,沒用任何框架,所有 JavaScript 皆手寫,正好可作為 Canvas 入門的簡易教材,或許能幫剛接觸 Canvas 的朋友建立概念。筆者接觸 Canvas 時間不長,技術尚淺,請多包涵。
廢話不多說,先上 Demo:飛機遊戲。這純屬娛樂之作,未朝正式遊戲方向規劃。
遊戲包含四個核心檔案:
index.html:入口頁面allSprite.js:精靈邏輯處理loading.js:資源預載處理data.js:初始化資料配置遊戲啟動需預載圖片與音訊。loading.js 核心邏輯如下:
loadImg: function(datas) {
var _this = this;
var dataIndex = 0;
function li() {
if (datas[dataIndex].indexOf("mp3") >= 0) {
var audio = document.createElement("audio");
document.body.appendChild(audio);
audio.preload = "auto";
audio.src = datas[dataIndex];
audio.oncanplaythrough = function() {
this.oncanplaythrough = null;
dataIndex++;
if (dataIndex === datas.length) {
_this.percent = 100;
} else {
_this.percent = parseInt(dataIndex / datas.length * 100);
li.call(_this);
}
};
} else {
preLoadImg(datas[dataIndex], function() {
dataIndex++;
if (dataIndex === datas.length) {
_this.percent = 100;
} else {
_this.percent = parseInt(dataIndex / datas.length * 100);
li.call(_this);
}
});
}
}
li();
},
function preLoadImg(src, callback) {
var img = new Image();
img.src = src;
if (img.complete) {
callback.call(img);
} else {
img.onload = function() {
callback.call(img);
};
}
}
在 data.js 以陣列存放資源路徑,依副檔名判斷類型:圖片用 preLoadImg(新建 Image 物件觸發載入回調),音訊建立 audio DOM 監聽 canplaythrough 事件(表示瀏覽器預估可不緩衝播放)。全部載入完畢後回調進入遊戲主迴圈。
遊戲物件眾多,統一封裝為 Sprite 類別,透過 painter(繪製器)與 behaviors(行為)區隔外觀與邏輯:
W.Sprite = function(name, painter, behaviors, args) {
if (name !== undefined) this.name = name;
if (painter !== undefined) this.painter = painter;
this.top = 0;
this.left = 0;
this.width = 0;
this.height = 0;
this.velocityX = 3;
this.velocityY = 2;
this.visible = true;
this.animating = false;
this.behaviors = behaviors;
this.rotateAngle = 0;
this.blood = 50;
this.fullBlood = 50;
// 依名稱初始化專屬屬性
if (name === "plan") { ... }
else if (name === "star") { ... }
else if (name === "badPlan") { ... }
else if (name === "missle") { ... }
else if (name === "boom") { ... }
else if (name === "food") { ... }
this.toLeft = this.toTop = this.toRight = this.toBottom = false;
this.outArcRadius = Math.sqrt((this.width/2 * this.width/2) * 2);
if (args) {
for (var arg in args) this[arg] = args[arg];
}
};
Sprite.prototype = {
constructor: Sprite,
paint: function() {
if (this.name === "badPlan") this.update();
if (this.painter !== undefined && this.visible) {
if (this.name !== "badPlan") this.update();
if (this.name === "plan" || this.name === "missle" || this.name === "badPlan") {
ctx.save();
ctx.translate(this.left, this.top);
ctx.rotate(this.rotateAngle);
this.painter.paint(this);
ctx.restore();
} else {
this.painter.paint(this);
}
}
},
update: function(time) {
if (this.behaviors) {
for (var i = 0; i < this.behaviors.length; i++) {
this.behaviors[i].execute(this, time);
}
}
}
};
爆炸、飛機射擊等動畫需多幀圖片,採用精靈表。兩張精靈表素材:


簡易精靈表繪製器實作:
var SpriteSheetPainter = function(cells) {
this.cells = cells || [];
this.cellIndex = 0;
};
SpriteSheetPainter.prototype = {
advance: function() {
if (this.cellIndex === this.cells.length - 1) this.cellIndex = 0;
else this.cellIndex++;
},
paint: function(sprite) {
var cell = this.cells[this.cellIndex];
context.drawImage(spritesheet, cell.x, cell.y, cell.w, cell.h,
sprite.left, sprite.top, cell.w, cell.h);
}
};
普通繪製器則直接在 paint 方法裡繪製單一圖形或圖片。
有了精靈類與繪製器,即可定義星星、飛機、子彈、爆炸、道具等物件。完整 allSprite.js 代碼(節錄):
(function(W) {
"use strict";
var planWidth = 24,
planHeight = 24,
missleWidth = 70,
missleHeight = 70,
boomWidth = 60;
// ... 後續定義各類 painter、behavior 並實例化精靈
})(window);
後續可依此架構擴充關卡、敵機 AI、分數系統等,打造更完整的遊戲體驗。