Before we get started we are going to need to setup our coding environment. This will be a quick and dirty copy paste solution for you.
We need two files. The first will be index.html and the second file will be: main.js Fill the index.html file with the following code…
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE HTML5> <html> <head> <script src="main.js"></script> <title>Caleb Jonasson Canvas Demo</title> </head> <body onload="onLoad()" style="margin:0px; padding:0px;"> <canvas id="canvas" width="800" height="400"></canvas> </body> </html> |
Now paste this code into the main.js file. The two files should be placed in the same directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var ctx = null; function onLoad() { // Get the context from the canvas ctx = document.getElementById("canvas").getContext("2d"); // Add an event listener document.addEventListener("click", registerInteraction, true); } var registerInteraction = function() { var x = window.event.pageX; var y = window.event.pageY; log("clicked: x"+x+", y"+y); } function log(content) { console.log(content); } |
Using the Context
You will notice that in the onLoad function we are getting the context of the canvas from the page. This ctx value will allow us to draw on the canvas. The common variable for the context is either “ctx” or “context”. This value is declared at the top of the document and will be public for everything to use.
We are going to start this lesson by drawing a background onto the canvas so we know where it starts and ends. Add the following code to the onLoad function.
1 2 | ctx.fillStyle = "#94B73E"; ctx.fillRect(0,0, 800, 400); |
The fill style is a variable sets the fill color of the item. The fillRect function simply fill a rectangle. The first two parameters are the x and y coordinates of where you would like to start drawing the rectangle. The second parameters are the ending coordinates of the rectangle. Upon running the script you will notice that we now have a solid background.
