Create the Canvas and draw on it
Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the
The HTML document structure is quite simple, as the game will be rendered entirely on the
<canvas> element. Using your favorite text editor, create a new HTML document, save it as
index.html, in a sensible location, and add the following code to it:
We have a
<title> and some basic CSS in the header. The body contains
<canvas> element has an
<script> and closing
To actually be able to render graphics on the
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d");
Here we're storing a reference to the
<canvas> element to the
canvas variable. Then we're creating the
ctx variable to store the 2D rendering context — the actual tool we can use to paint on the Canvas.
index.html in a browser to try it out.
ctx.beginPath(); ctx.rect(20, 40, 50, 50); ctx.fillStyle = "#FF0000"; ctx.fill(); ctx.closePath();
All the instructions are between the
closePath() methods. We are defining a rectangle using
rect(): the first two values specify the coordinates of the top left corner of the rectangle on the canvas, while the second two specify the width and height of the rectangle. In our case the rectangle is painted 20 pixels from the left side of the screen and 40 pixels from the top side, and is 50 pixels wide and 50 pixels high, which makes it a perfect square. The
fillStyle property stores a color that will be used by the
fill() method to paint the square, in our case, red.
ctx.beginPath(); ctx.arc(240, 160, 20, 0, Math.PI*2, false); ctx.fillStyle = "green"; ctx.fill(); ctx.closePath();
ycoordinates of the arc's center
- arc radius
- start angle and end angle (what angle to start and finish drawing the circle, in radians)
- direction of drawing (
falsefor clockwise, the default, or
truefor anti-clockwise.) This last parameter is optional.
fillStyle property looks different than before. This is because, just as with CSS, color can be specified as a hexadecimal value, a color keyword, the
rgba() function, or any of the other available color methods.
ctx.beginPath(); ctx.rect(160, 10, 100, 40); ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"; ctx.stroke(); ctx.closePath();
The code above prints a blue-stroked empty rectangle. Thanks to the alpha channel in the
rgba() function, the blue color is semi transparent.
Here's the full source code of the first lesson, running live in a JSFiddle:
Exercise: try changing the size and color of the given shapes.