Create a canvas element
Let’s change our
<body> again to use a canvas tag:
Now, we should have a nice canvas on our page, but it starts out blank. Time to draw!
Draw a rectangle
To draw a rectangle, we need to get the context element from the dom, then run a few functions on it:
1 2 3 4
Let’s walk through this. First, we get the canvas element by its
id like we did in the previous lesson. Next, we run the
getContext function that the canvas has on it. This will get us a context to draw on in two dimensions. There is a three dimensional context too, but it’s more difficult to use. Next, we set the canvas’s fill style to a gray color. This doesn’t do any drawing yet, it’s more like choosing a color in photoshop. Last, we’ll call the
fillRect function to draw a rectangle. This function has four parameters: x position, y position, width, and height.
Let’s tweak some of those parameters. Try a few different colors, even using rgba syntax like
rgba(32, 64, 128, 0.5). Trying making a rectangle of a different size or position. Try making more rectangles at different positions.
To make our coding life easier, let’s make a rectangle function. We’ll need to move our variables outside the ready function so the rectangle function can use it, plus we’ll want to allow the rectangle properties to be passed in as parameters.
1 2 3 4 5 6 7 8 9 10
Now it’s a lot easier to make rectangles by using our simple rectangle function.
Let’s add another function for drawing text, using the canvas function
1 2 3 4 5 6 7 8 9 10 11
fillText function works pretty similar to the rectangle function, except it needs a font. Now we have all the basic tools we need to draw stuff with canvas.