HTML Canvas: How to Get Started

Jamie Juviler
Jamie Juviler


If you’re learning HTML and getting the hang of the more straightforward elements, you might be a bit confused by its simplicity.

two people using HTML canvas on a computer

Is this really the language behind the incredible, interactive websites you’re seen in the past? There has to be something else (besides CSS) that takes HTML to the next level.

In many cases, that “something else” is canvas. Canvas is a powerful feature of HTML5 that allows us to draw images, and interact with graphics on the page, with some help from HTML’s sibling programming language, JavaScript.

In this post, you’ll learn the basics of how to use HTML canvas, including how to get started, and drawing basic shapes. Let’s dive in.

Download Now: 25 HTML & CSS Hacks [Free Guide]

What is HTML canvas?

HTML canvas is a way to create illustrations and graphics using HTML and JavaScript. A canvas is created in HTML with the <canvas> element. Canvas illustrations can also move and can be made interactive, making them great for infographics, data visualizations, animations, and even simple games.

To draw on the canvas, JavaScript must be used. While this makes learning canvas less accessible than other HTML concepts — you need to understand programming to an extent — it unlocks a myriad of possibilities for animated and interactive page content.

Once you understand canvas, it becomes a powerful tool for creating immersive websites. There’s far too much to cover in one post alone, so let’s stick to the basics for now.

How to Use HTML Canvas

In this section, we’ll walk through the basics of using canvas, including drawing simple lines, shapes, and images with JavaScript. But first, we need to create the HTML.

Set Up HTML Canvas

To add a canvas to a web page, we use the <canvas> tag. <canvas> adds a rectangular area to the page inside which you can draw shapes and animations.

Start by placing the following canvas element in the body of your HTML document:


<canvas id="test-canvas" width="300" height="200"></canvas>

The <canvas> tag includes the required id attribute, which allows us to reference the element in JavaScript. The code also includes width and height attributes that set the size (in pixels) of the canvas area. If width and height are not specified, these values default to 300 pixels and 150 pixels respectively.

Here’s what an empty canvas element looks like on a page. To make it visible, I’ve added a border with the style attribute.

See the Pen HTML canvas: empty canvas by HubSpot (@hubspot) on CodePen.

Not the most exciting, but this is where we’ll be adding our drawings with JavaScript.

Note that while you cna only set the canvas size in pixels within the <canvas> tag, you can use CSS to resize the canvas based on percentages. This is useful if you want to make the canvas full-screen. This video explains nicely how to do that:


Reference the Canvas in JavaScript

Now that we’ve placed our canvas element, we can access it with JavaScript in order to draw on it. We’ll use the getElementById() document method to target the <canvas> tag through the document object model and assign that to the variable canvas.


var canvas = document.getElementById("test-canvas");

Next, we have to create the rendering context of the canvas element. The rendering context creates a drawing object that specifies how we can draw with the canvas element. In this case, we’ll be drawing in two dimensions, so we’ll add the following code on the next line.


var context = canvas.getContext('2d');

We’re now ready to start drawing on our canvas.

Draw a Line

The first thing we’re going to draw is also the simplest: a straight line. But, to draw lines (and other shapes in canvas), we first need to understand how canvas coordinates work.

A canvas is a two-dimensional grid of pixels. Each pixel in the grid can be specified with a pair of X/Y coordinates. For example, our canvas is 300 x 200 pixels. The upper left corner of our canvas has the coordinates (0, 0), and the bottom right corner has the coordinates (300, 200).

I’ve drawn the same 300 x 200 canvas below — hover your cursor over the canvas area to see its current coordinates.

See the Pen HTML canvas: coordinates by HubSpot (@hubspot) on CodePen.

To draw a line with coordinates, we’ll use three methods. First, moveTo() sets where the line starts. Then, lineTo() sets where the line ends. Lastly, the stroke() method actually creates the line.

See the Pen HTML canvas: line by HubSpot (@hubspot) on CodePen.


Draw a Rectangle

Some geometry fans might insist that a line is not really a “shape.” Fair enough — let’s draw a rectangle. To do it, we use the rect() method. This method takes four parameters: The X coordinate of the upper left corner, the Y coordinate of the upper left corner, the width of the rectangle in pixels, and the height of the rectangle in pixels.


context.rect(20, 20, 200, 150);

After rect(), we’ll use the stroke() function again to draw the rectangle.

See the Pen HTML canvas: rectangle 1 by HubSpot (@hubspot) on CodePen.

Or, to fill in the rectangle, use the fill() function instead of stroke.

We can also draw a filled-in rectangle with the fillRect() method, which accepts the same parameters as rect(). This creates a filled-in rectangle that is black by default. You do not have to use the stroke() or fill() method here. To change the color of the rectangle, use the fillStyle property first, shown below:

See the Pen HTML canvas: rectangle 2 by HubSpot (@hubspot) on CodePen.


Draw a Circle

Next, let’s draw a circle. To do this in canvas, we use the arc() method. With arc, you specify the X and Y coordinates of the center, the radius of the arc, the starting angle (in radians) or the arc, and the stopping angle of the arc.

Since we want the arc to end where it started, we’ll set the starting angle to 0 radians and the stopping angle to 2 pi radians (if that doesn’t make sense, don’t worry about it — you don’t need to know calculus to use canvas!).


context.arc(100, 100, 50, 0, 2*Math.PI);

Then, use stroke() or fill() to draw the circle. This time, let’s use fill():

See the Pen HTML canvas: circle by HubSpot (@hubspot) on CodePen.

25 html and css coding hacks

Draw Shapes with Paths

In canvas, a path is the boundary of a shape, created by various methods listed in a series. With paths, you’re not limited to basic rectangles and circles — you can create virtually any kind of 2D shape you want.

To draw a shape with paths, use the following methods:

  • beginPath(): Signals that you’re creating a new shape.
  • moveTo(): Moves the path to a specific pair of coordinates without drawing a line.
  • lineTo(): Draws a line from the previous point on the path to a specific pair of coordinates.
  • arc(): Creates a curved line.
  • closePath(): Signals that you’re finished drawing the current shape.
  • fill(): Fills in the current path.
  • stroke(): Draws lines connecting the points in the current path.

When making a path, think of it like you’re physically drawing something on paper. Each function is like physically guiding your pen from one point to the next.

Check out the pen below as an example of what I mean — the path starts at the top of the star, then each line is made with its own lineTo() function. When finished, we color in the shape with fill().

See the Pen HTML canvas: paths by HubSpot (@hubspot) on CodePen.

Thanks to Tutorialspoint for providing the code for this example.

Draw Text

It’s also easy to create text in HTML canvas. We can use either the fillText() method (for filled-in text) or the strokeText() method (for text that is not filled in). Both methods require you to specify the text as well as the X and Y coordinates of the text area.


context.fillText("This is filled-in text.", 10, 40);

context.strokeText("This is not filled in.", 10, 80);

You can also set the font family, size, and other text styles with the font property, as shown below:

See the Pen HTML canvas: text 1 by HubSpot (@hubspot) on CodePen.

To add color to the text, use the fillStyle or strokeStyle properties:

See the Pen HTML canvas: text 2 by HubSpot (@hubspot) on CodePen.


Add Gradients to Shapes

Color gradients are another cool effect in canvas. There are two kinds of gradients you can make, linear gradients and radial gradients.

To create a linear gradient, use the method createLinearGradient() and assign it to a new gradient variable. This method takes for properties: the X and Y coordinates of the start of the gradient, followed by the X and Y coordinates of the end of the gradient.


var gradient = context.createLinearGradient(0, 0, 300, 0);

Adjusting these numbers changes the angle of the gradient inside the shape.

Next, we add two color stops with the addColorStop() method. These set the color for the start of the gradient and the color for the end of the gradient. With this method, we first set the position of the color in the gradient (a value between 0 and 1), then the color. The first color will smoothly transition into the second between stops.


gradient.addColorStop(0, "blue");

gradient.addColorStop(1, "red");

Lastly, we create our shape, then apply this gradient to a shape by setting the fillStyle of our shape to our gradient variable.


context.rect(20, 20, 200, 150);

context.fillStyle = gradient;


Here’s what our linear gradient looks like in action:

See the Pen HTML canvas: linear gradient by HubSpot (@hubspot) on CodePen.

Making a radial gradient is similar to making a linear one. To make a radial gradient, use the createRadialGradient() method. The first three parameters are the X location, Y location, and radius of the inner circle of the gradient, and the following three are the X location, Y location, and radius of the outer circle.


var gradient = context.createRadialGradient(120, 95, 10, 120, 95, 100);

Next, we add color stops like we did with our linear gradient:


gradient.addColorStop(0, "blue");

gradient.addColorStop(1, "red");

Finally, draw the shape and assign the radial gradient to the shape.


context.rect(20, 20, 200, 150);

context.fillStyle = gradient;


Here’s the final canvas:

See the Pen HTML canvas: radial gradient by HubSpot (@hubspot) on CodePen.


Add Images

Finally, let’s put an image on our canvas. The advantage of using images in an HTML canvas as opposed to putting as opposed to a standard <img> tag is that you can apply animations to your images and work them into your canvas illustrations.

To place an image, create a variable called image using the getElementById() method, then use the drawImage() method to place it inside the canvas. drawImage() has three required parameters: the ID of the image on the page, and the X and Y coordinates of the top left corner of the image. Optionally, you can also include the image’s width and height as parameters.


var image = document.getElementById("mountains");

context.drawImage(image, 0, 0, 300, 200);

Here’s what this code looks like paired with HTML:

See the Pen HTML canvas: image by HubSpot (@hubspot) on CodePen.

Level up your HTML game with canvas.

Learning canvas is like learning an HTML superpower. It might be difficult to see after just drawing lines and circles.

But, with some JavaScript trickery, it unlocks endless possibilities for unique and engaging browsing experiences. The next time you’re on a website with an interactive graphic or visualization, chances are that HTML canvas is making it all work.



Topics: HTML

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Tangible tips and coding templates from experts to help you code better and faster.