Javascript 特訓(xùn)-3
這一期梳理一下程序的入口豪娜,一個(gè)好的入門相當(dāng)于一個(gè)清晰的寫作文檔,定義了你需要實(shí)現(xiàn)哪些具體函數(shù)棚蓄。
// 傳入全局變量 this->global
var Engine = (function (global, width, height) {
// 定義繪制動(dòng)畫需要的參數(shù)
var doc = global.document,
win = global.window,
canvas = doc.createElement('canvas'),
ctx = canvas.getContext('2d'),
lastTime;
// 定義畫布為全局變量堕扶,便于其他 JS 文件調(diào)用
global.ctx = ctx;
// 定義畫布大小
canvas.width = width;
canvas.height = height;
doc.body.appendChild(canvas);
// 初始化函數(shù)
function init() {
// 還原
reset();
// 時(shí)間戳碍脏,記錄的是千分之一秒值
lastTime = Date.now();
// 主函數(shù)
main();
}
// 主函數(shù),畫布不斷刷新稍算,同時(shí)更新畫布內(nèi)容
function main() {
var now = Date.now();
dt = (now - lastTime) / 1000
// 畫面內(nèi)容更新典尾,顯示器未更新
update(dt);
// 畫面內(nèi)容渲染,顯示器未更新
render();
// 時(shí)間戳
lastTime = now;
// Javascript 每 1/60 FPS 刷新一次糊探,類似 setTimeout(main, 1000/60)
win.requestAnimationFrame(main);
}
// 還原函數(shù)
function reset() {
// 游戲重新執(zhí)行
// restart();
}
// 更新函數(shù)
function update(dt) {
updateUntities(dt);
// 檢驗(yàn)是否發(fā)生碰撞
// checkCollisions();
}
// 更新細(xì)節(jié)
function updateUntities(dt) {
// 玩家更新钾埂,一個(gè)玩家
player.update();
// 敵人更新,多個(gè)敵人
allEnemies.forEach(function (enemy) {
enemy.update(dt);
});
}
// 渲染函數(shù)
function render() {
var rowImages = [
'images/water-block.png', // 第一行圖片
'images/stone-block.png', // 第二行圖片
'images/stone-block.png', // 第三行圖片
'images/stone-block.png', // 第四行圖片
'images/grass-block.png', // 第五行圖片
'images/grass-block.png' // 第六行圖片
],
rows = 6,
cols = 5,
row,
col;
// 定位背景圖片位置科平,圖片大小 101 * 83
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 82);
}
}
// 渲染操作元素
renderUntities();
}
// 渲染操作元素函數(shù)
function renderUntities() {
// 玩家渲染
player.render();
// 敵人渲染
allEnemies.forEach(function (enemy) {
enemy.render();
});
}
// 素材加載褥紫,用到了上期的 Resources 對象
Resources.load([
'images/stone-block.png',
'images/water-block.png',
'images/grass-block.png',
'images/enemy-bug.png',
'images/char-boy.png'
]);
// 加載完觸發(fā)回調(diào)函數(shù)
Resources.onReady(init);
})(this, 505, 606);
Canvas 的機(jī)制還要多看網(wǎng)站學(xué)習(xí)下,感覺渲染的特別流暢瞪慧,功能好強(qiáng)大髓考。下一期開始動(dòng)畫對象的梳理,可以找畫畫好的人畫幾個(gè)有意思的圖片弃酌。