Skip to content

HTML5 - Canvas

The HTML <canvas> element provides a powerful and flexible way to draw graphics, animations, and manipulate images directly within a web page using JavaScript. It acts as a container for graphics; the actual drawing is done via the Canvas API or related APIs like WebGL.

The Canvas API primarily focuses on 2D graphics (the ‘2d’ context). For 3D graphics, you would typically use the WebGL API with the <canvas> element.

Canvas is widely used for data visualization, creating games, photo manipulation, real-time graphics rendering, and generating dynamic graphical elements.

You start by adding a <canvas> element to your HTML. It requires width and height attributes to define the size of the drawing surface (in CSS pixels). Any content placed between the opening and closing tags serves as fallback content for browsers that don’t support canvas.

<!DOCTYPE html>
<html>
<head>
<title>Canvas Example</title>
<style>
/* Add a border to visualize the canvas area */
#myDrawingCanvas {
border: 1px solid black;
background-color: #f0f0f0; /* Optional background */
}
</style>
</head>
<body>
<h1>My Canvas Drawing</h1>
<canvas id="myDrawingCanvas" width="400" height="300">
Your browser does not support the HTML5 canvas element.
<!-- Fallback content goes here -->
</canvas>
<script src="drawing.js"></script>
</body>
</html>

The <canvas> element itself is just a blank bitmap. To draw on it, you need to get its rendering context. The most common context is '2d', which provides the 2D drawing functions.

You obtain the context using the getContext() method in JavaScript:

// drawing.js
const canvas = document.getElementById('myDrawingCanvas');
// Check if canvas and getContext are supported
if (canvas.getContext) {
// Get the 2D rendering context
const ctx = canvas.getContext('2d');
console.log('Canvas context obtained:', ctx);
// --- Drawing code goes here ---
// Example: Draw a simple filled rectangle
ctx.fillStyle = 'red'; // Set the fill color
ctx.fillRect(10, 10, 150, 75); // Draw rectangle (x, y, width, height)
// Example: Draw outlined text
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.font = '30px Arial';
ctx.strokeText('Hello Canvas!', 50, 150); // Draw text (text, x, y)
} else {
console.error('Canvas not supported by this browser.');
// Handle lack of canvas support (e.g., display message from fallback content)
}

All drawing operations are performed on the ctx (context) object.

The canvas uses a grid system. The top-left corner of the canvas is coordinate (0, 0). X values increase to the right, and Y values increase downwards.

The 2D context provides methods for drawing various shapes, lines, text, and images.

  • ctx.fillRect(x, y, width, height): Draws a filled rectangle.
  • ctx.strokeRect(x, y, width, height): Draws the outline of a rectangle.
  • ctx.clearRect(x, y, width, height): Clears the specified rectangular area, making it transparent.

Paths are used to create complex shapes, lines, and curves. The process typically involves:

  1. ctx.beginPath(): Starts a new path.
  2. Use path methods like moveTo(x, y), lineTo(x, y), arc(x, y, radius, startAngle, endAngle), quadraticCurveTo(cp1x, cp1y, x, y), bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) to define the shape.
  3. ctx.closePath() (Optional): Closes the path by drawing a line back to the starting point.
  4. ctx.fill(): Fills the current path with the current fillStyle.
  5. ctx.stroke(): Draws the outline of the current path with the current strokeStyle and line styles.
// Example: Draw a triangle
ctx.beginPath();
ctx.moveTo(75, 50); // Start point
ctx.lineTo(100, 75); // Line to bottom right
ctx.lineTo(100, 25); // Line to top right
ctx.closePath(); // Line back to start
ctx.fillStyle = 'green';
ctx.fill(); // Fill the triangle
ctx.strokeStyle = 'darkgreen';
ctx.stroke(); // Outline the triangle
  • ctx.font = 'value': Sets the font properties (e.g., 'bold 48px serif').
  • ctx.fillText(text, x, y, [maxWidth]): Draws filled text.
  • ctx.strokeText(text, x, y, [maxWidth]): Draws outlined text.
  • ctx.textAlign = 'value': Sets text alignment (start, end, left, right, center).
  • ctx.textBaseline = 'value': Sets baseline alignment (top, hanging, middle, alphabetic, ideographic, bottom).
  • ctx.fillStyle = color | gradient | pattern: Sets the style used for filling shapes.
  • ctx.strokeStyle = color | gradient | pattern: Sets the style used for shape outlines (strokes).
  • ctx.lineWidth = value: Sets the width of lines.
  • ctx.lineCap = 'butt' | 'round' | 'square': Sets the appearance of line endings.
  • ctx.lineJoin = 'round' | 'bevel' | 'miter': Sets the appearance of corners where lines meet.
  • ctx.globalAlpha = value: Sets the transparency (0.0 = transparent, 1.0 = opaque).
  • Gradients: ctx.createLinearGradient(), ctx.createRadialGradient().
  • Patterns: ctx.createPattern(image, repetition).
  • ctx.drawImage(image, dx, dy): Draws an image (from <img>, <video>, or another <canvas>) onto the canvas at (dx, dy).
  • ctx.drawImage(image, dx, dy, dWidth, dHeight): Draws and scales the image.
  • ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight): Draws a portion (source sx, sy, sWidth, sHeight) of the image onto the canvas (destination dx, dy, dWidth, dHeight).

The context allows you to transform the coordinate system:

  • ctx.translate(x, y): Moves the origin (0,0) to (x, y).
  • ctx.rotate(angle): Rotates the canvas clockwise around the current origin (angle in radians).
  • ctx.scale(x, y): Scales the canvas horizontally by x and vertically by y.
  • ctx.transform(a, b, c, d, e, f) / ctx.setTransform(...): Modify the transformation matrix directly.
  • ctx.save(): Saves the current drawing state (styles, transformations).
  • ctx.restore(): Restores the most recently saved drawing state.

Canvas animations are typically created using JavaScript’s timing functions (setInterval, setTimeout) or, more commonly, requestAnimationFrame(). The basic loop involves:

  1. Clearing the canvas (e.g., ctx.clearRect(0, 0, canvas.width, canvas.height)).
  2. Updating animation variables (position, size, etc.).
  3. Drawing the scene in its new state.
  4. Requesting the next frame using requestAnimationFrame(yourDrawFunction).

The Canvas 2D API is universally supported by all modern desktop and mobile browsers. Older browsers like Internet Explorer 8 and below do not support it natively.

For complex graphics or games, consider using dedicated JavaScript libraries (like Fabric.js, Konva.js, p5.js for 2D, or Three.js, Babylon.js for WebGL/3D) that build upon the Canvas API and simplify many common tasks.