Using a HTML Canvas with Javascript
Published
Today we’ll be focusing on taking a HTML canvas element and using Javascript to make it do whatever we want.
First things first, using a canvas requires a bit of setup. You need to create a canvas element before you can access it from Javascript. You then need to get the element and its context. All the following canvas examples we’re going to show off will be using the same setup code:
const canvas = document.querySelector(`#my-canvas`)! as HTMLcanvasElement;
const ctx = canvas.getContext('2d')!;
This will give us the following base blank canvas (with added borders for visibility):
Drawing rectangles
Let’s fill this canvas with a background. To do so, we’ll need to get its size as well as select a color. Getting a canvas dimension is pretty simple as the canvas’ width and height are exposed as variables.
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
And it’s time to talk about an important point: the canvas coordinate have their origin in the top-left. That’s a point you need to keep in mind.
Let’s add a second, smaller blue rectangle. This second rectangle will be put on a separate layer on top of the first rectangle.
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
And lastly, we want to clear and reset a spot on the canvas:
ctx.clearRect(40, 40, 30, 30);
Drawing Images
Drawing an image on a canvas works in pretty much the same way as a rectangle with one added specificity. You need to load the image before you can draw it on the canvas.
const img = new Image();
img.src = '/android-chrome-192x192.png';
img.onload = (e) => {
// If you do not want to resize the image
// ctx.drawImage(img,0,0);
// Enforce a width and a height
ctx.drawImage(img, 0, 0, 100, 100);
};
You can avoid having to wait for the image to load if you use a base64 URL encoded. These look like this “data:image/gif;base64,R0lGO[…ommited…]GBYAOw==“. We won’t be showcasing them here as you’ll more often just be using regular images.
Making the canvas interactive
Let’s make our canvas interactive, we’ll want to respond to a click by placing a small image at the click’s coordinates.
We’ll be reusing the image loading code from before but without drawing the image itself. By adding an event listener on the canvas, we can listen to every onclick event on it. We can then get the coordinates of the click by using both the offsetX and offsetY properties.
We can then just render the image at the click’s location.
const img = new Image();
img.src = '/android-chrome-192x192.png';
canvas.onclick = (e) => {
const { offsetX: x, offsetY: y } = e;
console.log(`clicked on: { x: ${x}, y: ${y} }`);
ctx.drawImage(img, x, y, 20, 20);
};
Try it on this Interactive Canvas below, the canvas click coordinates will be printed to the console.
And that’s all for now. All the examples we’ve gone through use a 2D canvas but you’ll find that the HTML canvas can also support 3D and that there even are video game engines written in Javascript built on this Canvas element.