Week 1

This article is created to explain the code we worked on last week. I improvised the lesson this week so there is some bad code, but it's okay. Hopefully I will address all the questions you had about the code. If you have any more, I would suggest checking out the resources on W3schools or the MDN web docs. That said, here is the code:

window.onload = function() {
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d");
	ctx.fillStyle = "#000";
	ctx.fillRect(10, 10, 20, 20);

First off, window.onload. This function is defined by the browser, as in the window object. As you can see, we actually define a variable in the same line that we set it to equal window.onload. This type of function declaration is actually done a lot in Javascript.

Next line. The document object is defined by the browser. This function getElementById() allows us to pick an object from the web browser and manipulate it in Javascript. In this case, we get the canvas, which is what we draw on.

The ctx variable. This is our drawing context. It's an important object, and we will always use it to draw to our canvas. Here is the article about this object on MDN.

ctx.fillStyle = "#000";
The fillStyle variable refers to the color that objects will be filled. We can make an outline of a rectangle, but instead we "filled" it. #000 is a hexidecimal number. You can read more about hex and how that relates to colors here. The part about hex is about midway through that article.

ctx.fillRect(10, 10, 20, 20);

Here, we tell the canvas graphics to fill a rectangle. The parameters are (x coordinate, y coordinate, width, height). The x and y coordinates refer to the top-left of the rectangle too. You can see the official MDN documentation and play with the function here.

I also want to mention that we run this code once. When the window loads, we draw the rectangle once and then stop. This is because we are not clearing the screen as you would in an actual game.