Canvas & Graphics
Overview
The `<canvas>` element is like a blank digital whiteboard on your web page. By itself, it does absolutely nothing. It is just an empty transparent rectangle.
However, by using JavaScript, you can draw pixels, lines, shapes, images, and text onto this whiteboard. This is the technology used to build web-based video games (like Browser Mario), complex data charts, and 3D graphics (using WebGL).
Syntax
In HTML, you just declare the canvas and give it a width and height. You MUST give it an `id` so your JavaScript can find it.
<!-- Just an empty box waiting to be painted -->
<canvas id="gameBoard" width="800" height="600">
Your browser does not support the canvas element.
</canvas>To draw on the canvas, you grab the element in JS, get its 'context' (which is the drawing tool), and then start issuing commands like 'draw a rectangle here' or 'color it blue'.
const canvas = document.getElementById("gameBoard");
// Get the 2D drawing tool
const ctx = canvas.getContext("2d");
// Set the paint color to blue
ctx.fillStyle = "blue";
// Draw a rectangle at (x:50, y:50) with width:150, height:100
ctx.fillRect(50, 50, 150, 100);Common Pitfalls
- The <canvas> tag's width and height attributes are NOT the same as CSS width and height. If you stretch a small canvas using CSS, the drawing inside will become incredibly blurry and pixelated.
- Interview tip: Canvas draws in 'immediate mode' (fire and forget pixels). SVG draws in 'retained mode' (objects you can manipulate later).
Real-World Example
Drawing a simple red circle (like a notification dot) using Canvas:
// 1. Get the canvas
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// 2. Start a new drawing path
ctx.beginPath();
// 3. Define the circle (x, y, radius, startAngle, endAngle)
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
// 4. Fill it with red
ctx.fillStyle = "red";
ctx.fill();