๐ŸŽ“ A1Learner
๐Ÿ”
0 of 50 lessons completed

HTML Canvas Basics

The canvas element is a blank drawing surface on a page. A small script gives the browser the steps for a drawing.

A blank surface

The canvas element starts blank. Its width and height set the drawing size.

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

Painting a rectangle

JavaScript is the browser instruction language. The JavaScript course teaches it. The script finds the canvas by its id. Then it paints a green rectangle.

<script>
const board = document.getElementById("drawing");
const pen = board.getContext("2d");
pen.fillStyle = "green";
pen.fillRect(10, 10, 80, 50);
</script>

Drawing a line

These steps draw a line from one corner to the other. The line runs across the blank surface.

<script>
const board = document.getElementById("drawing");
const pen = board.getContext("2d");
pen.beginPath();
pen.moveTo(0, 0);
pen.lineTo(200, 100);
pen.stroke();
</script>

Example

<!DOCTYPE html>
<html lang="en">
<head>
<title>My First Drawing</title>
</head>
<body>
<h1>My First Drawing</h1>
<canvas id="drawing" width="240" height="120" style="border: 1px solid black;"></canvas>
<script>
const board = document.getElementById("drawing");
const pen = board.getContext("2d");
pen.fillStyle = "green";
pen.fillRect(10, 10, 80, 50);
pen.beginPath();
pen.moveTo(0, 100);
pen.lineTo(240, 0);
pen.stroke();
</script>
<p>A green rectangle and a black line sit on the canvas.</p>
</body>
</html>

Key points

  • canvas: a blank drawing surface on a page
  • A canvas element needs a script to show a drawing
  • Width and height set the size of the drawing surface
  • A canvas with no script stays blank

In this example, the heading names the page. The canvas element gives a drawing surface with a border. The script finds the canvas by its id and asks for its drawing tool. The script paints a green rectangle and draws a line across the surface. The paragraph under the canvas describes the drawing in words.

Note

A canvas drawing is a picture on the page. Page text around it stays ordinary text.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What makes a drawing appear on a canvas?