Skip to main content

HTML Canvas Graphics

The <canvas> element is used to draw graphics on a web page, such as rectangles, gradients, and text.


What is HTML Canvas?

The <canvas> element is used to draw graphics on the fly with JavaScript. The element itself is only a container; you must use JavaScript to do the actual drawing. Canvas has methods for drawing paths, boxes, circles, text, and images, and it is supported by all major browsers.


Canvas Examples

A canvas is a rectangular area on the page. By default it has no border and no content.

Note: Always give it an id (to refer to it in a script) and width and height attributes to set its size. To add a border, use the style attribute.

Example

A basic, empty canvas with a border.

Prompt
A page with a basic, empty 200x100 canvas (id myCanvas) given a 1px solid black border via the style attribute.
Output: complete HTML page

Canvas markup

The basic markup for a canvas element.

index.html
<canvas id="myCanvas" width="200" height="100"></canvas>

Add a JavaScript

After making the canvas area, you add JavaScript to do the drawing. You get the canvas with getElementById, then call getContext("2d") to get the drawing context, and use its methods. Here are several examples.

Draw a Line

Drawing a line with moveTo, lineTo, and stroke.

Prompt
A page with a 200x100 canvas and a script that draws a line from (0,0) to (200,100) using getContext('2d'), moveTo, lineTo and stroke.
Output: complete HTML page

Draw a Circle

Drawing a circle with arc and stroke.

Prompt
A page with a 200x100 canvas and a script that draws a circle centered at (95,50) with radius 40 using arc and stroke.
Output: complete HTML page

Draw a Text

Drawing filled text with fillText.

Prompt
A page with a 200x100 canvas and a script that draws filled text "Hello World" in 30px Arial at (10,50) using fillText.
Output: complete HTML page

Stroke Text

Drawing outlined text with strokeText.

Prompt
A page with a 200x100 canvas and a script that draws outlined text "Hello World" in 30px Arial at (10,50) using strokeText.
Output: complete HTML page

Draw Linear Gradient

Filling a rectangle with a linear gradient.

Prompt
A page with a 200x100 canvas and a script that fills a rectangle with a horizontal linear gradient from red to white.
Output: complete HTML page

Draw Circular Gradient

Filling a rectangle with a radial gradient.

Prompt
A page with a 200x100 canvas and a script that fills a rectangle with a radial (circular) gradient from red to white.
Output: complete HTML page

Draw Image

Drawing an existing image onto the canvas with drawImage.

Prompt
A page with a hidden image (id scream) and a 200x100 canvas, plus a script that draws the image onto the canvas at (10,10) using drawImage.
Output: complete HTML page