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

MethodDescriptionExample
fillRect(x, y, width, height)Draws a filled rectanglectx.fillRect(10, 10, 100, 50);
strokeRect(x, y, width, height)Draws a rectangular outlinectx.strokeRect(10, 10, 100, 50);
clearRect(x, y, width, height)Clears the specified rectangular areactx.clearRect(0, 0, canvas.width, canvas.height);
beginPath()Begins a new pathctx.beginPath();
moveTo(x, y)Moves the path to the specified pointctx.moveTo(10, 10);
lineTo(x, y)Adds a line to the pathctx.lineTo(100, 100);
arc(x, y, radius, startAngle, endAngle)Adds an arc to the pathctx.arc(50, 50, 40, 0, Math.PI * 2);
fill()Fills the current pathctx.fill();
stroke()Strokes the current pathctx.stroke();
fillText(text, x, y)Draws filled textctx.fillText('Hello', 10, 50);
strokeText(text, x, y)Draws text outlinectx.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/

Konva.js

2D canvas library with object model, event handling, and animations.

https://konvajs.org/
< Previous: YouTube EmbedsNext: HTML SVG >