HTML Canvas Tutorial
Learn how to draw graphics and create animations using the HTML Canvas element
Introduction to HTML Canvas
The HTML <canvas>
element is used to draw graphics on a web page via JavaScript. It provides a powerful API for creating animations, games, data visualizations, and more.
Basic Syntax:
Basic Canvas Examples
1. Basic Canvas Drawing
Draw a simple rectangle on a canvas element.
2. Drawing Different Shapes
Draw rectangles, circles, and lines on a canvas.
3. Drawing Text and Styles
Add text and apply different styles to your canvas drawings.
Canvas Drawing Methods
Method | Description | Example |
---|---|---|
fillRect(x, y, width, height) | Draws a filled rectangle | ctx.fillRect(10, 10, 100, 50); |
strokeRect(x, y, width, height) | Draws a rectangular outline | ctx.strokeRect(10, 10, 100, 50); |
clearRect(x, y, width, height) | Clears the specified rectangular area | ctx.clearRect(0, 0, canvas.width, canvas.height); |
beginPath() | Begins a new path | ctx.beginPath(); |
moveTo(x, y) | Moves the path to the specified point | ctx.moveTo(10, 10); |
lineTo(x, y) | Adds a line to the path | ctx.lineTo(100, 100); |
arc(x, y, radius, startAngle, endAngle) | Adds an arc to the path | ctx.arc(50, 50, 40, 0, Math.PI * 2); |
fill() | Fills the current path | ctx.fill(); |
stroke() | Strokes the current path | ctx.stroke(); |
fillText(text, x, y) | Draws filled text | ctx.fillText('Hello', 10, 50); |
strokeText(text, x, y) | Draws text outline | ctx.strokeText('Hello', 10, 50); |
Advanced Canvas Techniques
1. Canvas Animation
Create smooth animations using requestAnimationFrame.
2. Image Manipulation
Load and manipulate images on canvas.
3. Simple Game Example
A basic game loop with keyboard controls.
(Game would be implemented with JavaScript - use arrow keys to move)
Canvas Best Practices
Performance
- Use
requestAnimationFrame
for animations - Minimize canvas state changes (save/restore)
- Use multiple canvases for complex UIs
- Clear only the area that changed, not the whole canvas
- Consider using offscreen canvas for complex drawings
Code Organization
- Separate drawing logic from game/app logic
- Use object-oriented approach for complex projects
- Implement a proper game loop for games
- Use helper functions for common drawing operations
- Consider using canvas libraries for complex projects
Canvas Libraries and Frameworks
p5.js
A JavaScript library for creative coding, with a focus on making coding accessible.
https://p5js.org/Fabric.js
A powerful and simple JavaScript HTML5 canvas library with SVG parsing capabilities.
http://fabricjs.com/