Computer scienceFrontendHTMLAdvanced elements

HTML Canvas Graphics

7 minutes read

There are a lot of ways to make your website more fun and interactive, and one of them is Canvas Graphics. Canvas Graphics allows you to control your graphics, images, and text dynamically using JavaScript. In this topic, we will cover the basic shapes that you can draw on your canvas. Let's start!

HTML Canvas Graphics

In this step, you will get an idea of what you can do with canvas, alongside the code snippets and tasks to get the hang of the <canvas> element.

The HTML element <canvas> is used to display the container for graphics. In order to draw the graphics, you must use JavaScript. Using <canvas> you can draw paths and boxes, combine photos and text, or just create simple animations. The Canvas is your oyster!

Indeed, <canvas> provides a lot of opportunities to play around with graphics, but it's not really essential to the user. However, It can definitely create a very unique effect with a lot of benefits.

So, what is a canvas? Canvas is a rectangular container that by default has no borders and no content. Still, it has two attributes by default, width and height. The default values of these attributes are initially 300 pixels wide and 150 pixels high. The code snippet below shows the basic HTML syntax for a simple blank canvas:

<canvas id="canvas" width="200" height="100"></canvas>

The code output looks like this:

White rectangle with the black thin border

To refer to the canvas in a script, always specify the id attribute to the <canvas> element, as well as width and height attributes to define the desired container size of the canvas. If you want to enhance the size of the canvas container, specify the border with the style attribute.

Drawing shapes with canvas

Before you start drawing something on the canvas, there is one important method you need to learn about first. The method is called .getContext(). The .getContext() method returns a drawing context on the canvas. If the context identifier is not supported or the canvas has been set to a different context mode, it will return null. The syntax looks like this:

HTMLCanvasElement.getContext(contextType)

You've already covered the entire syntax, except for the argument contextType. The contextType argument is a string containing the context identifier that defines the drawing context associated with the canvas. There are a lot of possible values that you can check on the Developer Mozilla. But in this topic, we will be only using the 2d.

The 2d is creating a CanvasRenderingContext2D object that represents a two-dimensional rendering context. CanvasRenderingContext2D is a part of the Canvas API that provides 2D rendering context for the drawing surface of a <canvas> element.

After creating the <canvas> element, it's time to add JavaScript code. To render 2D context, you will call .getContext() method on the <canvas> element. The code should look like this:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');

Now that we've covered HTMLCanvasElement.getContext(), you should be able to draw shapes on the canvas by learning some of the new methods from the next steps.

As previously said, in order to work with canvas you must use JavaScript. In this step, we will go through drawing basic shapes (rectangles and circles) on the canvas using JavaScript.

The <canvas> element supports two types of primitive shapes: rectangles and paths. In order to create other shapes, you must combine two or more paths.

First, let's draw the rectangle. To draw a rectangle on the canvas, you need to use the following three functions:

  • fillRect(x, y, width, height) draws a filled rectangle.

  • strokeRect(x, y, width, height) draws a rectangular outline.

  • clearRect(x, y, width, height) clears the specified rectangular area, making it transparent.

Let's take a closer look at the parameters. The x and y specify the position of the canvas relative to the origin. Width and height specify the size of the rectangle. In the code snippet below, you can see how to use these functions:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
	ctx.fillRect(25, 25, 100, 100);
    ctx.clearRect(45, 45, 60, 60);
    ctx.strokeRect(50, 50, 50, 50);

Here is the output of the code:

Black square on the white background with two white black-bordered squares in it

Next, let's draw a circle! In order to draw a circle, we need to use a path. For drawing a circle, you will need three methods:

  • beginPath() begins a path, or resets the current path.

  • arc(x, y, r, sAngle, eAngle) creates an arc/curve.

  • stroke() draws the path on the canvas.

The arc() method works with a lot of parameters. The x and y specify the x-coordinate and y-coordinate, r the radius, sAngle and eAngle specify the start and the end angle.

In the code snippet below you can see how these methods are implemented:

const c = document.getElementById("canvas");
const ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(75, 75, 60, 0, 7);
ctx.stroke();

Here is the code output:

The white circle with the thin black border on the white background

Draw a text

In the last step, you will learn how to draw text on canvas. In order to draw a text, you only need two methods:

  • fillText(text, x, y) draws filled text on the canvas.

  • strokeText(text, x, y) draws text with no fill on the canvas.

Take a look at the parameters. As always, both methods x and y stand for x and y coordinates of the starting point of the text. The text parameter specifies the text that will be written on the canvas. I'm sure you have already written your first 'Hello world' program, but let's do it again! But this time, let's "draw" it! In the code snippet below, you can see how to draw the text using only the fillText() method:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.font = '50px serif';
ctx.fillText('Hello world', 50, 90);

Here is the code output:

The serif text black color – Hello World on the white backgrund

The code snippet below shows the strokeText() method:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.font = '50px serif';
ctx.strokeText('Hello world', 50, 90);

In the code output below you can see the difference between these two methods:

Black bordered serif text white color – Hello World on the white background

Conclusion

In this topic, you've learned how to create a canvas on your website and draw different shapes. The following topics were covered:

  • .getContext() method.

  • Drawing shapes on a canvas.

  • Drawing text on a canvas.

Canvas provides a lot of possibilities. In this topic, we've only scratched the surface. Still, you can do a lot of things with basic shapes. Let's test your knowledge!

32 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo