← Back to HTML Course | Chapter 6: Canvas, SVG & Media | Lesson 1 of 6

HTML Canvas

Imagine hanging a large, blank whiteboard on your classroom wall. The whiteboard itself is clean and empty, but it comes with a tray of colorful dry-erase markers and an eraser. To draw a map or write notes, you have to pick up a marker and draw on it yourself. An HTML canvas is that digital whiteboard. By itself, the canvas element is just a blank container on your webpage. To draw shapes, write text, or create animations, you must write JavaScript scripts to paint on it. It is the perfect tool for building online drawing boards, custom charts, interactive games, or dynamic photo editors.

The Canvas Container

The canvas tag defines a blank drawing board on your webpage. It is a simple container element that requires explicit width and height attributes to define its resolution, and some fallback text inside for older browsers.

Note: Always specify the resolution of your canvas using HTML attributes, and use CSS to scale the element dynamically.

Warning: If you omit width and height attributes, the browser will set the canvas to a tiny default size of 300x150 pixels.

Example: The Canvas Container

markup
<canvas id="myCanvas" width="300" height="150">
  Your browser does not support the canvas element.
</canvas>

The Drawing Context

Before you can draw on your canvas, you must write a script to capture the element's ID and declare its drawing context (like 2d), which prepares the browser with the tools and coordinate system needed to paint on it.

Note: The 2d context provides a standard coordinate system where (0,0) is located in the top-left corner of the canvas.

Warning: Ensure the webpage finishes loading before your script tries to capture the canvas context, or your code will return an error.

Example: The Drawing Context

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById('myCanvas').getContext('2d');
</script>

Drawing Rectangles

The 2D canvas context provides three easy-to-use methods to draw rectangles directly on your board: fillRect (to draw a solid rectangle), strokeRect (to draw a hollow rectangular outline), and clearRect (to erase an area).

Note: Combine fillStyle and strokeStyle properties with your rectangle methods to style your shapes with custom colors.

Warning: Always set your fillStyle or strokeStyle colors before calling your drawing methods, or they will render in standard black.

Example: Drawing Rectangles

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(10, 10, 100, 50);
</script>

Drawing Lines and Paths

To draw custom shapes, curves, or circles, you must use path methods. Drawing a path is like drawing with a pencil: you tell the browser to place the pencil on the board (beginPath), trace the lines (lineTo), and paint the result (stroke or fill).

Note: Use the arc method to trace circular lines and shapes on your canvas easily.

Warning: Always call beginPath before tracing new lines to prevent your shapes from blending together incorrectly.

Example: Drawing Lines and Paths

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.beginPath();
  ctx.lineTo(150, 80);
  ctx.stroke();
</script>

Clearing and Updating the Canvas

To create dynamic animations, interactive drawing boards, or game frames, you must frequently update your canvas. You do this by erasing the entire board using clearRect, updating your shape coordinates, and painting the new frames in rapid succession.

Note: Use the requestAnimationFrame method to create smooth, high-performance web animations on your canvas.

Warning: If you do not clear your canvas before drawing a new frame, your animated shapes will leave trail marks across the screen.

Example: Clearing and Updating the Canvas

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.clearRect(0, 0, 200, 100);
  ctx.fillRect(10, 10, 50, 50);
</script>

Drawing Text on Canvas

The fillText and strokeText methods let you draw text directly onto the canvas, with the font property controlling size and typeface beforehand. Unlike regular HTML text, canvas text is just pixels — it cannot be selected, searched, or read by screen readers.

Note: Set the font property before calling fillText, since canvas remembers the current font setting for every subsequent drawing operation.

Warning: Text drawn on canvas is invisible to screen readers and search engines — never use it for content that needs to be accessible or indexable.

Example: Drawing Text on Canvas

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.font = '20px Arial';
  ctx.fillText('Hello Canvas', 10, 50);
</script>

Drawing Images onto Canvas

The drawImage method lets you place an existing image file onto the canvas, and you can also control its position and size, or even crop and scale it. This is the basis for building things like image editors, filters, or dynamic thumbnail generators entirely in the browser.

Note: Always wait for the image's onload event to fire before calling drawImage, or the canvas may end up blank.

Warning: Drawing images from a different domain onto canvas can trigger cross-origin restrictions that block reading the canvas data back out afterward.

Example: Drawing Images onto Canvas

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const img = new Image();
  img.src = 'photo.jpg';
  img.onload = function () {
    document.getElementById('myCanvas').getContext('2d').drawImage(img, 0, 0);
  };
</script>

Saving Canvas as an Image

The toDataURL method converts whatever is currently drawn on the canvas into a downloadable image file, encoded as a base64 data URL. This is how in-browser tools let users export a chart, drawing, or edited photo as an actual PNG or JPEG file.

Note: Use toDataURL("image/png") for the highest quality output, or pass "image/jpeg" with a quality argument for smaller file sizes.

Warning: toDataURL will throw a security error if the canvas contains any image drawn from a different origin that does not allow cross-origin access.

Example: Saving Canvas as an Image

markup
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const dataURL = document.getElementById('myCanvas').toDataURL('image/png');
</script>
Common Mistakes
  1. Defining the canvas resolution using CSS styles instead of HTML attributes, which can stretch your drawings out of shape.
  2. Forgetting to call the stroke or fill methods when drawing paths, resulting in invisible lines on your canvas.
  3. Attempting to draw on the canvas in your scripts before the context is fully loaded.
Chapter Summary
  • The canvas tag defines a blank, styleable drawing container on your webpage.
  • Capture the canvas ID in your scripts and declare its 2D context to prepare the coordinate system.
  • Draw rectangles, circles, and custom shapes on your canvas using path methods, and create smooth animations using clearRect and coordinate updates.
Browser Support

Standard HTML5 canvas and 2D contexts are supported natively by all modern web browsers.

🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.