HTML Canvas - Dynamic Graphics

The HTML5 Canvas element provides a JavaScript API for drawing graphics dynamically. Canvas is used for games, visualizations, image editing, and animations.

Creating a Canvas

The <canvas> element creates a drawable region on the page with specified width and height.

Canvas content is created using JavaScript - the element itself is just a container.

Get the drawing context using getContext('2d') for 2D graphics or getContext('webgl') for 3D.

Always set width and height attributes on the canvas element (not just CSS) to define the drawing area resolution.

<!-- Canvas element -->
<canvas id="myCanvas" width="500" height="400" style="border: 1px solid black;">
  Your browser doesn't support canvas.
</canvas>

<script>
// Get canvas and context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Now you can draw
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
</script>

Drawing Shapes

fillRect(x, y, width, height) draws a filled rectangle.

strokeRect(x, y, width, height) draws a rectangle outline.

clearRect(x, y, width, height) clears a rectangular area.

Use beginPath(), moveTo(), lineTo(), arc(), and other path methods to draw custom shapes.

Call fill() to fill paths or stroke() to draw outlines.

<canvas id="shapes" width="400" height="300"></canvas>

<script>
const ctx = document.getElementById('shapes').getContext('2d');

// Filled rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 100, 80);

// Outlined rectangle
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.strokeRect(150, 20, 100, 80);

// Triangle
ctx.beginPath();
ctx.moveTo(75, 150);
ctx.lineTo(125, 250);
ctx.lineTo(25, 250);
ctx.closePath();
ctx.fillStyle = 'green';
ctx.fill();

// Circle
ctx.beginPath();
ctx.arc(300, 200, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'orange';
ctx.fill();
</script>

Drawing Text

fillText(text, x, y) draws filled text at the specified position.

strokeText(text, x, y) draws text outline.

Set font property to specify font size and family (e.g., '20px Arial').

Set textAlign ('left', 'center', 'right') and textBaseline ('top', 'middle', 'bottom') for positioning.

measureText(text) returns the width of text for precise layout.

<canvas id="text" width="500" height="200"></canvas>

<script>
const ctx = document.getElementById('text').getContext('2d');

// Set font
ctx.font = '30px Arial';

// Filled text
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 50, 50);

// Outlined text
ctx.strokeStyle = 'blue';
ctx.lineWidth = 1;
ctx.strokeText('Outlined Text', 50, 100);

// Centered text
ctx.textAlign = 'center';
ctx.fillText('Centered', 250, 150);
</script>

Colors, Styles, and Gradients

fillStyle and strokeStyle set colors for fills and strokes (colors, gradients, or patterns).

createLinearGradient(x1, y1, x2, y2) creates a linear gradient.

createRadialGradient(x1, y1, r1, x2, y2, r2) creates a radial gradient.

Add color stops with addColorStop(position, color) where position is 0 to 1.

lineWidth, lineCap, and lineJoin control stroke appearance.

<canvas id="gradients" width="400" height="300"></canvas>

<script>
const ctx = document.getElementById('gradients').getContext('2d');

// Linear gradient
const linearGrad = ctx.createLinearGradient(0, 0, 200, 0);
linearGrad.addColorStop(0, 'red');
linearGrad.addColorStop(0.5, 'yellow');
linearGrad.addColorStop(1, 'green');
ctx.fillStyle = linearGrad;
ctx.fillRect(20, 20, 200, 100);

// Radial gradient
const radialGrad = ctx.createRadialGradient(300, 180, 10, 300, 180, 80);
radialGrad.addColorStop(0, 'white');
radialGrad.addColorStop(1, 'blue');
ctx.fillStyle = radialGrad;
ctx.fillRect(220, 100, 160, 160);
</script>

Images and Pixel Manipulation

drawImage() draws an image, canvas, or video onto the canvas.

drawImage(img, x, y) draws at natural size.

drawImage(img, x, y, width, height) draws scaled.

drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) draws a portion of the source image.

getImageData() and putImageData() allow direct pixel manipulation.

<canvas id="images" width="600" height="400"></canvas>

<script>
const ctx = document.getElementById('images').getContext('2d');
const img = new Image();

img.onload = function() {
  // Draw image at natural size
  ctx.drawImage(img, 10, 10);
  
  // Draw scaled
  ctx.drawImage(img, 200, 10, 150, 150);
  
  // Draw cropped section
  ctx.drawImage(img, 50, 50, 100, 100,  // source crop
                400, 10, 100, 100);       // destination
  
  // Pixel manipulation
  const imageData = ctx.getImageData(0, 0, 100, 100);
  // Modify imageData.data array
  ctx.putImageData(imageData, 10, 200);
};

img.src = 'photo.jpg';
</script>

Animation with Canvas

Animations require repeatedly clearing and redrawing the canvas.

Use requestAnimationFrame() for smooth animations synchronized with the browser's refresh rate.

Clear the canvas with clearRect() or fillRect() over the entire canvas.

Update object positions, then redraw all objects in each frame.

Store object state in JavaScript variables between frames.

<canvas id="animation" width="400" height="300"></canvas>

<script>
const canvas = document.getElementById('animation');
const ctx = canvas.getContext('2d');

let x = 0;
let y = 150;
let dx = 2;

function animate() {
  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // Draw circle
  ctx.beginPath();
  ctx.arc(x, y, 20, 0, 2 * Math.PI);
  ctx.fillStyle = 'blue';
  ctx.fill();
  
  // Update position
  x += dx;
  if (x > canvas.width || x < 0) dx = -dx;
  
  // Next frame
  requestAnimationFrame(animate);
}

animate();
</script>