The HTML5 <canvas>
element provides a powerful, pixel-based drawing surface within your web page. Unlike SVG, which uses vector graphics and treats each shape as a separate DOM element, Canvas is a raster graphics API. You draw directly onto a bitmap, making it excellent for high-performance animations, games, and dynamic visual effects where you need pixel-level control.
Let’s dive into the fundamentals of using JavaScript with the HTML5 Canvas.
1. Setting Up Your Canvas
First, you need the <canvas>
element in your HTML. It’s good practice to give it an id
so you can easily reference it in JavaScript and define its width
and height
. If you don’t specify these, the default size is 300×150 pixels.
HTML
<!DOCTYPE html>
<html>
<head>
<title>JS Canvas Tutorial</title>
<style>
body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: #f0f0f0; }
canvas { border: 2px solid #333; background-color: #fff; }
</style>
</head>
<body>
<canvas id="myDrawingCanvas" width="800" height="400"></canvas>
<script>
// Your JavaScript code will go here
</script>
</body>
</html>
2. Getting the Drawing Context
To actually draw on the canvas, you need to get its “rendering context.” For 2D graphics (which is what we’ll focus on), you’ll use '2d'
.
JavaScript
const canvas = document.getElementById('myDrawingCanvas');
// Check if the browser supports canvas
if (canvas.getContext) {
const ctx = canvas.getContext('2d'); // This is your drawing tool!
// Now you can start drawing using 'ctx' methods
} else {
// Canvas is not supported
alert('Your browser does not support the HTML5 Canvas.');
}
The ctx
object is where all the drawing magic happens. It provides properties to set colors and line styles, and methods to draw shapes, text, and images.
3. Drawing Basic Shapes
a. Rectangles
Rectangles are the simplest shapes to draw.
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 a rectangular area, making it fully transparent.
Before drawing, you can set fill and stroke styles:
ctx.fillStyle = 'color'
: Sets the color for subsequentfillRect
andfill
operations.ctx.strokeStyle = 'color'
: Sets the color for subsequentstrokeRect
andstroke
operations.ctx.lineWidth = number
: Sets the width of lines for stroke operations.
JavaScript
const canvas = document.getElementById('myDrawingCanvas');
const ctx = canvas.getContext('2d');
// Draw a filled blue rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 150, 100);
// Draw a red outlined rectangle
ctx.strokeStyle = 'red';
ctx.lineWidth = 4;
ctx.strokeRect(250, 50, 150, 100);
// Clear a portion of the first rectangle
ctx.clearRect(80, 80, 90, 40);
b. Paths (Lines and Custom Shapes)
For anything more complex than a rectangle, you’ll use paths. A path is a sequence of sub-paths that describe a shape.
ctx.beginPath()
: Starts a new path. This is crucial before drawing a new, distinct shape.ctx.moveTo(x, y)
: Moves the “pen” to a starting point without drawing.ctx.lineTo(x, y)
: Draws a straight line from the current point to the specified point.ctx.closePath()
: Draws a straight line from the current point back to the start of the current sub-path, closing it.ctx.stroke()
: Draws the outline of the current path.ctx.fill()
: Fills the current path.
JavaScript
// Draw a triangle
ctx.beginPath(); // Start a new path
ctx.moveTo(450, 50); // Top point
ctx.lineTo(550, 150); // Bottom-right point
ctx.lineTo(350, 150); // Bottom-left point
ctx.closePath(); // Closes the triangle by drawing to the start
ctx.fillStyle = 'green';
ctx.fill(); // Fill the triangle
// Draw a simple line
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.lineTo(300, 250);
ctx.strokeStyle = 'purple';
ctx.lineWidth = 2;
ctx.stroke();
c. Circles and Arcs
ctx.arc(x, y, radius, startAngle, endAngle, counterClockwise)
is used to draw circles or parts of circles. Angles are measured in radians. A full circle is 2 * Math.PI
radians.
JavaScript
// Draw a filled circle
ctx.beginPath();
ctx.arc(150, 300, 50, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle (radians)
ctx.fillStyle = 'orange';
ctx.fill();
// Draw a half-circle outline
ctx.beginPath();
ctx.arc(350, 300, 50, 0, Math.PI); // Half circle from 0 to 180 degrees
ctx.strokeStyle = 'darkblue';
ctx.lineWidth = 3;
ctx.stroke();
4. Drawing Text
You can also draw text on the canvas.
ctx.font = 'font-style font-variant font-weight font-size font-family'
: Sets the font properties.ctx.fillText('text', x, y)
: Draws filled text.ctx.strokeText('text', x, y)
: Draws outlined text.ctx.textAlign = 'start' | 'end' | 'left' | 'right' | 'center'
: Horizontal alignment.ctx.textBaseline = 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'
: Vertical alignment.
JavaScript
ctx.font = '40px "Comic Sans MS"';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.fillText('Canvas Fun!', canvas.width / 2, 380); // Centered horizontally at the bottom
5. Drawing Images
You can draw images onto the canvas using ctx.drawImage()
. You need an Image
object or an existing <img>
element.
JavaScript
const img = new Image();
img.src = 'your-image.png'; // Replace with a valid image path
img.onload = () => { // Wait for the image to load
// Draw the image at position (450, 200) with its original size
ctx.drawImage(img, 450, 200);
// Draw the image scaled to 100x100
ctx.drawImage(img, 650, 200, 100, 100);
};
Always ensure the image is loaded (img.onload
) before attempting to draw it to prevent errors.
Conclusion
The HTML5 Canvas API is a powerful tool for client-side graphics. While it requires a more programmatic approach (pixel by pixel), its performance and flexibility make it ideal for games, complex data visualizations, and interactive animations. This tutorial covers the fundamental drawing operations; the Canvas API also supports transformations (scaling, rotating, translating), gradients, patterns, and more advanced pixel manipulation, opening up a world of possibilities for dynamic web content.