Building Interactive Graphics with HTML5 Canvas
The canvas element establishes a fixed-resolution bitmap within a webpage. Distinct from image tags, it does not utilize src attributes for content sourcing. Dimension control relies strictly on width and height properties. Before any graphics appear, the execution environment must request a rendering context object, typically the 2d context using getContext('2d').
Coordinate Mapping
The drawing grid originates at the top-left corner, designated as (0,0). Positional arguments relative to this origin determine where elements appear. Increasing values move elements down and to the right.
Geometric Primitives
The API offers specific methods for immediate rendering and procedural pathing.
Rectangles Direct manipulasion supports three modes:
- Fill: Populates a box defined by top-left coordinates and dimensions.
- Stroke: Outlines a box without filling the interior.
- Clear: Removes existing pixels, restoring transparency.
Vector Paths Complex shapes utilize the path system. The process begins by resetting the current path buffer. Subsequent coordinate commands extend the vector. Final, the shape is rendered via stroking the edges or filling the interior volume.
Essential pathing calls include:
beginPath(): Starts a new trajectory.moveTo(x, y): Relocates the virtual pen.lineTo(x, y): Draws a connection to the next point.closePath(): Connects the last point back to the start.fill()/stroke(): Applies visual styles to the completed path.
Example Setup and Drawing:
const surface = document.getElementById('canvas-surface');
const painter = surface.getContext('2d');
painter.fillStyle = 'cyan';
painter.lineWidth = 4;
// Constructing a geometric figure
painter.beginPath();
painter.moveTo(15, 15);
painter.lineTo(85, 15);
painter.lineTo(50, 85);
painter.lineTo(15, 85);
painter.fill();
Styling Configuraton
Visual traits are managed through context properties.
Color Values
Properties like fillStyle and strokeStyle accept various inputs:
- Named strings (e.g., "blue")
- Hex notation (e.g., "#FF0000")
- RGB/RGBA functions (e.g., "rgba(255, 0, 0, 0.5)")
Attributes
lineWidth: Thickness of the drawn line.globalAlpha: Opacity factor affecting all subsequent strokes.globalCompositeOperation: Determines how new layers interact with existing content (e.g., 'source-over', 'destination-out').
Incorporating External Data
Images
Load an image resource first. Once loaded, call drawImage passing the object and starting coordinates (x, y).
Text
Configure the font family and size beforehand. fillText renders solid glyphs, while strokeText draws character outlines. Both allow optional width parameters for clipping.
const asset = new Image();
asset.src = '/img/logo.png';
asset.addEventListener('load', () => {
painter.drawImage(asset, 0, 0);
});
painter.font = '20px monospace';
painter.fillText('Processing', 50, 100);