參考:
1、image onload事件:http://www.runoob.com/jsref/event-img-onload.html(贊)
2、canvas的drawImage無法顯示圖像:https://segmentfault.com/q/1010000002877796
(嘗試setInterval(render, 10);就會發現圖檔顯示出來了。)
3、addeventlistener的捕獲與冒泡:https://my.oschina.net/u/867090/blog/387380

5、發現網上已經有很多人寫了:http://www.qdfuns.com/notes/13275/a66ea9c091c5cc4d0007abaf83d223ca:storey-21
6、随機迷宮算法:随機迷宮算法 、http://bbs.9ria.com/thread-156150-1-1.html
mytest.js
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 550;
canvas.style.position = "absolute";
canvas.style.left = "calc(50% - 350px)";
canvas.style.top = "calc(50% - 275px)";
document.body.appendChild(canvas);
// load images
var bgImage = new Image();
bgImage.src = "images/background.png";
var heroImage = new Image();
heroImage.src = "images/hero.png";
var wallImage = new Image();
wallImage.src = "images/wall.png";
// Game data
var hero = {
x: 0,
y: 0
};
var aa = new Array(); //定義一維數組
for(i = -1; i <= 14; i++) {
aa[i] = new Array(); //将每一個子元素又定義為數組
for(j = -1; j <= 13; j++) {
aa[i][j] = false;
}
}
var x2 = 0;
var y2 = 0;
var notWall = function(x , y) {
return !aa[x][y];
}
// random labyrinth
// Game data init
var reset = function() {
// hero init
hero.x = 100;
hero.y = 100;
// wall init
for(i = 0; i <= 13; i++) {
for(j = 0; j <= 12; j++) {
aa[i][j] = Math.random() > 0.5 ? true : false;
}
}
}
// Game expression
var render = function() {
// draw background
ctx.drawImage(bgImage, 0, 0, 800, 550);
// draw hero
ctx.drawImage(heroImage, hero.x, hero.y);
// draw wall
for (m = 0; m <= 13; ++m)
for (n = 0; n <= 12; ++n)
if (aa[m][n]) ctx.drawImage(wallImage, 50*m+60, 36.5*n+40);
ctx.fillText("hero positon: x=" + hero.x + ",y=" + hero.y, 100, 100);
}
var speed = 4;
addEventListener("keydown", function (e) {
x2 = Math.floor((hero.x-44)/50);
y2 = Math.floor((hero.y-32)/34.9);
if (e.key == "ArrowUp" && hero.y > 32 && notWall(x2 , y2-1)) {
hero.y -= speed;
}
if (e.key == "ArrowDown" && hero.y < canvas.height - 73 && notWall(x2 , y2+1)) {
hero.y += speed;
}
if (e.key == "ArrowLeft" && hero.x > 44 && notWall(x2-1 , y2)) {
hero.x -= speed;
}
if (e.key == "ArrowRight" && hero.x < canvas.width - 73 && notWall(x2+1 , y2)) {
hero.x += speed;
}
}, false);
var testGame = function() {
reset();
setInterval(render, 13);
}
testGame();