HTML Canvas

Here are some things that will help us get started with the canvas element.

Parts 1-4 of this excellent guide will be a helpful resource if you get stuck!

The Canvas

The HTML Canvas is a tool that lets us manually draw onto a bitmap. A bitmap is a grid of different colored pixels.

Here is how we take a canvas element and prepare it for drawing:

1let canvas = document.querySelector("#myCanvas");
2canvas.width = window.innerWidth;
3canvas.height = window.innerHeight;
4let ctx = canvas.getContext("2d");

In this code, the ctx variable is what we use to do all the fun drawing work.

Draw a square

In the world of HTML Canvas (like many other situations in programming), the X and Y are equal to 0 at the top left corner. X increases from left to right, and Y increases from top to bottom. To draw (or fill) a 100x100 pixel square, starting at the top left corner, we first set the fillStyle:

1ctx.fillStyle = 'red';

Then, we use the function fillRect like so:

1ctx.fillRect(0,0,100,100);

Discuss randomness together in class:

  • go over random numbers again
  • discuss how we might make random colors

And now..... USER INPUT!!

As you could probably guess, there are ways to respond to things the user does on a page, which we have not explored yet through javascript!

In reality, javascript has access to knowledge of everything the user does: clicking, moving, typing, resizing the window, etc.

In order to use this information, our code generally follows the same pattern in all cases: we use Event Listeners. It won't hurt to read up on what these are, but here are the main steps to use event listeners.

  • Get an HTML element with document.querySelector that we want to "listen" for user events and act on them

    1let myCanvas = document.querySelector("#myCanvas")
  • Create a listener function that has one parameter. Typically this parameter is named event.

    1let mouseClickListener = function(event){
    2  console.log(event);
    3}
    In our listener function, the event parameter will be magically filled with a ton of really descriptive info about the user event that just occured. We can do anything we like with this information.
  • In JS terminology, we "attach" the listener to the element, and specify which event to listen for:

    1myCanvas.addEventListener("click",mouseClickListener)
    Here are a bunch of event types we can listen for: click, dblclick, mouseover, mouseout, mouseenter, mouseleave, mousedown, mouseup, mousemove,
Here is another nice overview of mouse events if it helps!

Nested for-loop

This is a classically confusing bit of code that is crucial to understand in any programming language! With time it's going to make sense, so don't worry if it looks crazy.

1for(let i=0; i<10;i++){
2  for(let j=0; j<10;j++){
3    console.log(i,j);
4  }
5}

What is the output going to be for this code?

I consider understanding this to be a major coding milestone, so congrats!