HTML Canvas
According to the dictionary (Collins Cobuild Advanced Learner's Digital Edition), canvas can be defined as 'A piece of canvas or similar material on which an oil painting can be done.' One of the features of HTML is an element known as canvas. The HTML canvas element is used to draw graphics in the browser window using JavaScript.
HTML canvas is the best method to draw ârasterâ graphics on a web application. It has an API called the Canvas API that provides 2D and 3D drawing contexts. In this article, I'll be referring to the 2D drawing context.
The canvas element is only a container for graphics. You must use a script to draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. HTML Canvas is supported on all major browsers (Chrome, Edge, Firefox, Safari, and Opera).
Things you can do with HTML Canvas:
- HTML Canvas Can Draw Text.
- HTML Canvas Can Draw Graphics.
- HTML Canvas Can be Animated.
- HTML Canvas Can be Interactive.
- HTML Canvas Can be Used in Games.
Example
To define the element, we use the canvas keyword which needs to have an id attribute to be accessed in the JavaScript file.
<canvas id="artCanvas" width="400" height="400"></canvas>
The id can be named anything that makes the element unique. In addition, we can optionally give width and height values as attributes. The Canvas element can be styled with CSS just like any other block-level element. For example, we can add a border around the canvas.
<canvas id="artCanvas" width="400" height="400" style="border: 1px solid #000000;"></canvas>
You are not only limited to inline CSS styling, it is possible to use an external stylesheet which is linked to the HTML page in the head section.
Painting with JavaScript
Step 1: First, you must find the canvas element using the getElementById() method.
const canvas = document.getElementById("artCanvas");
You are free to name the variable that finds the canvas element to anything you want.
Step 2: Create a drawing object because you will need a drawing object for the canvas. The getContext() is a built-in HTML object which has properties and methods for drawing.
const ctx = canvas.getContext("2d");
Step 3: You can draw on the canvas by setting the fill style of the drawing object to the color red.
ctx.fillStyle = "#FF0000";
The fillStyle property can be a CSS color name, a gradient, or a pattern. The default fillStyle is black. The fillRect(x, y, width, height) method draws a rectangle, filled with the fill style, on the canvas.
ctx.fillRect(0, 0, 150, 75);
One thing to note is that regardless of what values you use in the fillRect() method for 'width' and 'height', the rectangle size will always be constrained by the size defined on the canvas inside the HTML file. In this case 400px by 400px.

Canvas Coordinates
The HTML canvas is a two-dimensional grid. The upper-left corner of the canvas has the coordinates (0,0). We previously saw this method used: fillRect(0, 0, 150, 75). This means: "Start at the upper-left corner (0,0) and draw a 150 x 75 pixels rectangle."
Drawing a Line
To draw a straight line on the canvas, use the following methods:
moveTo(x,y)- defines the starting point of the line.lineTo(x,y)- defines the ending point of the line.- To draw the line, you must use the
stroke()method.
// Drawing a line
ctx.moveTo(50, 50);
ctx.lineTo(200, 200);
ctx.strokeStyle = 'green'
ctx.stroke();
The code block above draws a line of 200px length starting from the coordinates (50,50).

Drawing a Circle
Canvas allows us to draw several shapes including a circle. A circle can be drawn with the methods below:
beginPath()- begins a path.arc(x,y,r,startangle,endangle)- creates an arc/curve. To create a circle witharc(): Set the start angle to 0 and the end angle to 2*Math.PI. The x and y parameters define the x and y-coordinates of the center of the circle. The r parameter defines the radius of the circle.- Then use the
stroke()method to draw the circle.
// Drawing a circle
ctx.beginPath();
ctx.arc(200, 200, 100, 0, 2*Math.PI);
ctx.strokeStyle = 'blue'; // Color of edges of the circle
ctx.lineWidth = 10; // Thickness of the edges of the circle
ctx.fillStyle ="orange" // Color of inside of the circle
ctx.stroke();
ctx.fill();
The code block above draws a circle starting at coordinates (200, 200), has a radius of 100, a start angle of 0, and an end angle of 2 multiplied by Pi.

Gradients in Canvas
Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors. There are two different types of gradients:
createLinearGradient(x,y,x1,y1)- creates a linear gradient.createRadialGradient(x,y,r,x1,y1,r1)- creates a radial/circular gradient.- x and y are the starting coordinates of the gradient colors, x1 and y1 are width and height values for the gradient color and r is the radius of the circular gradient.
- Once we have a gradient object, we must add two or more color stops.
- The
addColorStop()method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1. - To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).
JavaScript example of creating a linear gradient:
// Create a gradient
const grd = ctx.createLinearGradient(10, 10, 200, 0);
grd.addColorStop(0, "blue");
grd.addColorStop(1, "orange");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(100, 100, 150, 80);

Similarly, we can create a radial gradient using the method shown below:
// Create radial gradient
const grd = ctx.createRadialGradient(150, 150, 20, 150, 90, 100);
grd.addColorStop(0, "purple");
grd.addColorStop(1, "lime");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(100, 100, 150, 80);

HTML Canvas Text
To draw text on a canvas, the most important property and methods are:
- font - defines the font properties for the text.
fillText(text,x,y)- draws "filled" text on the canvas.strokeText(text,x,y)- draws text on the canvas (no fill).
Using fillText()
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
The example above sets the font to 30px "Arial" and writes a filled text on the canvas.
Using strokeText()
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);
The example above sets font to 30px "Arial" and writes a text, with no fill, on the canvas.
Adding Color and Centering Text
ctx.beginPath();
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
The code block above sets the font to 30px "Comic Sans MS" and writes a filled red text in the center of the canvas.

HTML Canvas Images
To draw an image on a canvas, use the drawImage() method like this - drawImage(image,x,y)
JavaScript example for drawing images:
const img = document.getElementById("flying-cow");
ctx.drawImage(img, 10, 10);
The id property of 'flying-cow' is accessible from the HTML DOM. In this case, it has been hidden for us to display the image inside the canvas.
<img src="images/flying-cow.png" alt="Flying cow" id="flying-cow" style="display: none;">
And this is how it renders:

Other Canvas Methods
Paths are a collection of points in the 2D pixel grid in the canvas. They are drawn with the help of this API. Each shape in a path that you draw is called a âsubpathâ according to the W3C documentation.
beginPath()andclosePath(): All the shapes that you draw are added to the current path. If you call stroke or fill, later on, it will apply that to all of the shapes youâve drawn in the current path. To prevent that, you divide your drawing by calling beginPath and closePath.
// Green path
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();
// Purple path
ctx.beginPath();
ctx.strokeStyle = "purple";
ctx.moveTo(50, 0);
ctx.lineTo(150, 130);
ctx.stroke();

The code block above draws a green line and a purple line that intersect each other because of the beginPath() method. We have already seen moveTo() and lineTo(), but below is a table with more JavaScript methods to manipulate the HTML canvas.
| Method | Description | Example Usage |
|---|---|---|
quadraticCurveTo() and bezierCurveTo() |
Draws a quadratic/cubic bezier curve starting from the last point in the shape, passing through the control points (cpx1, cpy1 and cpx2,cpy2 ), and ending at x,y. A Bezier curve is just a âsmoothâ curve that passes through intermediate âcontrolâ points with given ending points. Note that the curve doesnât have to exactly pass through the control points â it can be smoothed out. | quadraticCurveTo(cpx1,cpy1,x,y) or bezierCurveTo(cpx1,cpy1,cpx2,cpy2,x,y) |
arcTo() |
This is a slightly complicated method to use. Suppose the current point in the path is x0,y0 â then arcTo will draw an arc that has two tangents connecting these two pairs of points (x1,y1) & (x0,y0) and (x1,y1) & (x2,y2). The arcâs radius will be the one given. The greater the radius, the farther out the arc will be from x1,y1. If you havenât used moveTo yet, then x0,y0 will by default be 0,0. | arcTo(x1,y1,x2,y2,radius) |
| ImageData() | The ImageData object can be used to manipulate individual pixels. It has width, height, and data properties. data is a Uint8ClampedArray which contains the individual pixel data in a series of (R,G,B,A) bytes for the top-most pixel to the bottom-right pixel. | Examples below... |
You can get an ImageData object with the following methods createImageData() |
This creates an ImageData object of width and height sw and sh , defined in CSS pixels. All the pixels will be initialized to transparent black (hex R,G,B=0, and also A=0). | createImageData(sw,sh) |
getImageData() |
Returns a copy of the canvasâs pixels in the rectangle formed by sx,sy,sw,sh in an ImageData object. Pixels outside the canvas are set to transparent black. | getImageData(sx,sy,sw,sh) |
putImageData() |
Copies the pixel values in imagedata into the canvas rectangle at dx,dy. (The last four 'dirty' arguments are optional). If you provide the last four arguments, it will only copy the dirty pixels in the image data (the rectangle formed at dirtyX, dirtyY of dimensions dirtyWidth * dirtyHeight). Not passing the last four arguments is the same as calling putImageData(imagedata, dx,dy,0,0,imagedata.width,imagedata.height). |
putImageData(imagedata, dx,dy,dirtyX,dirtyY,dirtyWidth,dirtyHeight) |
Wrapping Up
As demonstrated in this article, the HTML canvas element depends on the coordinates with respect to the defined width and height of the canvas element. These coordinates are almost always the first 2 numbers when we call a method for example the fillRect(x, y, width, height) method.
The HTML canvas API has been used to create some amazing products for entertainment, education, and even marketing purposes. Here is a good YouTube tutorial about HTML canvas on a channel called freeCodeCamp.org. This tutorial requires a decent understanding of JavaScript. Here is another article that I wrote about HTML. Feel free to share some feedback via this contact form.
~ Until then, happy codingâď¸.
