HTML5 Canvas Basics: Getting Started with 2D Games
HTML5 Canvas Basics: Getting Started with 2D Games
HTML5 Canvas is a powerful tool for rendering 2D graphics in the browser, making it the perfect starting point for web-based game development. Let's explore the fundamental methods you'll use constantly.
1. Setting Up the Context
Before you can draw anything, you need to get the canvas element and its 2D rendering context:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
2. Drawing Rectangles (fillRect & strokeRect)
Rectangles are the most basic shape. fillRect draws a filled rectangle, while strokeRect draws its outline.
ctx.fillStyle = 'blue'; // Determine inner color
// x, y, width, height
ctx.fillRect(10, 10, 50, 50); // Draws a 50x50 blue square at x:10, y:10
ctx.strokeStyle = 'red'; // Determine border color
ctx.strokeRect(70, 10, 50, 50); // Draws a red outline
3. Drawing Circles and Arcs (arc)
To draw circles or curves, you define a path and use arc(x, y, radius, startAngle, endAngle, counterclockwise). Note that angles are measured in radians, not degrees.
- x, y: the coordinates of the arc's center.
- radius: the arc's radius.
- startAngle, endAngle: starting and ending angle in radians (A full circle is
2 * Math.PI).
ctx.beginPath(); // Start a new path
// x: 100, y: 75, radius: 50
// startAngle: 0, endAngle: 2 * Math.PI (a full circle)
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'yellow';
ctx.fill();
// Drawing a half-circle outline (arc)
ctx.beginPath();
ctx.arc(200, 75, 40, 0, Math.PI); // Half circle (180 degrees)
ctx.strokeStyle = 'green';
ctx.stroke();
4. Advanced Colors and Linear Gradients
You can set colors using standard CSS color names, HEX, RGB, or RGBA for transparency. You can also create gradients!
// Simple color transparency using RGBA
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // 50% transparent red
// Creating a Linear Gradient: createLinearGradient(x0, y0, x1, y1)
// The parameters represent the start (x0, y0) and end (x1, y1) point
const gradient = ctx.createLinearGradient(0, 0, 150, 0); // Horizontal gradient
gradient.addColorStop(0, 'red'); // Start color at offset 0
gradient.addColorStop(0.5, 'yellow'); // Middle color at offset 0.5
gradient.addColorStop(1, 'green'); // End color at offset 1
ctx.fillStyle = gradient; // Set gradient as the fill style
ctx.fillRect(10, 150, 150, 50);
5. Rendering Advanced Text (fillText, textAlign, textBaseline)
Rendering text on a canvas is straightforward, but you can also control its alignment and baseline (vertical origin point).
ctx.font = '24px Arial'; // Define font family and size
ctx.fillStyle = 'white';
// Horizontal alignment (left, center, right, start, end)
ctx.textAlign = 'center';
// Vertical alignment (top, hanging, middle, alphabetic, ideographic, bottom)
ctx.textBaseline = 'middle';
// Drawing the text (text string, x, y)
ctx.fillText('Center Aligned Text', canvas.width / 2, canvas.height / 2);