Our First Main Function we will call fitToWindow. The point of this function is to make sure that no matter the size of the window in our browser, the game will be able to adapt. We need to add this otherwise the game will only be visible for one type of window size.
function fitToWindow() {
let screen_margin = 10;
WIDTH = Math.min(TARGET_WIDTH, window.innerWidth - screen_margin);
HEIGHT = Math.min(TARGET_HEIGHT, window.innerHeight - screen_margin - 300);
WIDTH = Math.max(WIDTH, 100);
HEIGHT = Math.max(HEIGHT, 100);
CANVAS.width = WIDTH;
CANVAS.height = HEIGHT + GUI_HEIGHT;
PRERENDERED_CANVAS.width = WIDTH;
PRERENDERED_CANVAS.height = HEIGHT + GUI_HEIGHT;
}
I recommend that you dont change this code, because it should be like this for all window sizes.
Our next function is the main function.
function main() {
// code
}
There are multiple things that will go inside this function. It creates a new HTML5 canvas element, adds listeners for input and contains the main loop.
Basically, how the code runs, is it loops through the main function, aways listing for keyboard inputs, then going to different functions.
First we will initlize some variables, these say that our screen is 2d.
CANVAS = document.createElement("canvas");
CTX = CANVAS.getContext("2d");
Next, we will initialize another canvas for quickly drawing static objects.
PRERENDERED_CANVAS = document.createElement("canvas");
PRERENDERED_CTX = PRERENDERED_CANVAS.getContext("2d");
fitToWindow(); // Set the size of both canvas, from our previous function
We will attempt to find a document element with a specific id, otherwise attach the canvas to the document body.
attach_to = document.getElementById('game_window');
if (attach_to == null) attach_to = document.body;
attach_to.appendChild(CANVAS);
We want to prevent scrolling with arrowkeys and spacebar.