The HTML canvas
element is used to draw graphics using JavaScript. It gives you the ability to draw things like lines, arcs, rectangles, and images. A canvas, created using the canvas
tag, only represents the container for where the graphics will be drawn. Let's take a look at how to define a canvas in HTML, and look at examples of how to draw on it.
Defining a Canvas
To create a canvas, we need to create a canvas
element. We can do this by using the canvas
tag.
<canvas></canvas>

Nothing appears because a canvas is an invisible element.
Width and Height
We can set the width and height of the canvas using the width
and height
attributes. Let's take a look at how to set the width and height of the canvas.
<canvas width="400" height="200">
</canvas>
Change background color
You can change the background color of a canvas using CSS:
Get the context of the canvas
To draw on a canvas, we need to get the context of the canvas. We can do this by using the getContext
method.
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
Here are the value values when you use getContext
:
2d
: This stands forCanvasRenderingContext2D
webgl
: This stands forWebGLRenderingContext
webgl2
: This stands forWebGL2RenderingContext
bitmaprenderer
: This stands forImageBitmapRenderingContext
Drawing a line
You can draw a line by using the lineTo
method. Let's take a look at how to draw a line on a canvas. We'll create a line from the top left corner of the canvas to the bottom right corner.
Drawing a rectangle
You can draw a rectangle by using the rect
method. Let's take a look at how to draw a rectangle on a canvas. We'll create a rectangle from the top left corner of the canvas to the bottom right corner.
Drawing a Circle
You can draw a circle by using the arc
method. Let's take a look at how to draw a circle on a canvas.
Drawing Text
You can draw text by using the fillText
method. Let's take a look at how to draw text on a canvas.
Drawing Stroke Text
You can draw stroke text by using the strokeText
method. Let's take a look at how to draw stroke text on a canvas.
Drawing Linear Gradients
You can draw linear gradients by using the createLinearGradient
method. Let's take a look at how to draw linear gradients on a canvas.
Drawing Radial Gradients
You can draw radial gradients by using the createRadialGradient
method. Let's take a look at how to draw radial gradients on a canvas.