In this article we will start to learn about the HTML canvas. We will do a sequence of articles about the HTML5 canvas where we explore the topic in debt. This will be the first part of that article sequence. At the end of this article sequence your will be familiar with almost all aspects of the HTML5 canvas. Once you finished it you will be able to create some stunning interactive and animated canvas designs.
What will we learn about the HTML canvas in this article?
- Setup our HTML canvas
- How to resize yourHTML canvas
- Learn how to draw shaped on your canvas
So lets jump right in and lets write some code
<!DOCTYPE html><html lang=”en”><head><metacharset=”UTF-8″><metaname=”viewport”content=”width=device-width, initial-scale=1.0″><metahttp-equiv=”X-UA-Compatible”content=”ie=edge”><title>Document</title></head><body></body></html>
<body><canvas id=”canvas”></canvas><script src=”main.js”></script></body>
Now we have everything in place to start resizing our HTML canvas
Now lets go over to your main.js file and add a variable we name canvas. As a value for this variable we want the HTML canvas we have in our HTML file. We can do this with document.getElementById(‘canvas’). Since we gave our canvas an ID of canvas inside of our HTML, we can now grab it and use it as a value for our canvas variable inside of our main.js file.
let canvas = document.getElementById(‘canvas’); //Saving the HTML canvas into a JS variablecanvas.height = window.innerHeight; //Set the height of the canvas equal to the height of the windowcanvas.width = window.innerWidth; //Set the width of the canvas equal to the width of the window
Now lets actually draw something on our html canvas
To draw on our canvas we need to have a context for our canvas. This should be a 2d or 3d context. For now we will go with a 2d context and save it in a variable like this:
let c = canvas.getContext(‘2d’);
- X start position will be x pixels to the right from the top left corner
- Y start position will be x pixels to the bottom from the top
- The 2 points above will give you your starting point of the rectangle
- Now the width and height you added will make out the size of your rectangle
So if we create this line of code:
c.fillRect(100, 100, 100, 100);
c.fillRect(100, 100, 100, 100);c.fillRect(200, 200, 100, 100);c.fillRect(300, 300, 100, 100);