现在,我正在搞乱 HTML5 并使用 JavaScript 制作一个简单的 2D Tile 地图。进展顺利,但我意识到我不能把所有东西都放在一个巨大的函数中。
我正在尝试使canvas
其他context
函数可以访问全局变量。现在,它仅在“加载”时可用......我如何自己制作它?当我放置canvas
并context
创建变量时......我得到了错误Uncaught TypeError: Cannot call method 'getContext' of null
这是我的SSCCE:
// HTML5 JS Tile Example
// Set return 2D array of map
function loadMap(map) {
if (map == 1) {
return [
[67, 67, 67, 67, 67, 67, 67, 67, 67, 190, 190, 67, 1, 1, 1, 1], [67, 393, 343, 343, 343, 343, 343, 343, 343, 190, 190, 448, 1, 166, 166, 1], [67, 343, 343, 393, 343, 343, 343, 343, 343, 343, 343, 448, 1, 166, 166, 1], [67, 1, 1, 1, 439, 1, 1, 1, 343, 13, 13, 13, 43, 166, 166, 1], [67, 1, 166, 166, 166, 166, 166, 1, 343, 13, 343, 448, 1, 166, 166, 1], [67, 1, 166, 166, 166, 166, 166, 1, 343, 13, 343, 448, 1, 166, 166, 1], [67, 1, 166, 166, 166, 166, 166, 1, 343, 13, 343, 448, 1, 319, 1, 1], [67, 1, 25, 1, 166, 321, 25, 1, 343, 13, 343, 343, 343, 343, 343, 67], [67, 424, 424, 424, 13, 424, 424, 424, 343, 13, 343, 343, 343, 394, 343, 67], [370, 13, 13, 13, 13, 13, 13, 13, 13, 13, 67, 67, 343, 343, 343, 67], [67, 67, 67, 67, 67, 67, 67, 67, 67, 370, 67, 67, 67, 67, 67, 67]];
}
}
// On load...
window.onload = function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
var tiles = [];
var board = loadMap(1);
canvas.width = 512;
canvas.height = 352;
// 2. SET UP THE MAP TILES
for (x = 0; x <= 520; x++) {
imageObj = new Image(); // new instance for each image
imageObj.src = "line_tile/t" + x + ".png";
tiles.push(imageObj);
}
var theX;
var theY;
// 3. DRAW MAP BY ROWS AND COLS
for (x = 0; x <= 10; x++) {
for (y = 0; y <= 15; y++) {
theX = x * 32;
theY = y * 32;
context.drawImage(tiles[board[x][y]], theY, theX, 32, 32);
}
}
};
在线示例: http: //mystikrpg.com/html5/