HTML Canvas

The HTML <canvas> element is a versatile and powerful tool for rendering 2D graphics, animations, and even interactive visuals using JavaScript. It provides a blank canvas where you can dynamically draw shapes, images, text, and more directly in the browser.

What Is HTML Canvas?

The <canvas> element is a part of HTML5. It defines a rectangular area (or canvas) in your web page, which you can draw on using the Canvas API.

Basic Canvas Syntax

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>

Accessing the Canvas Context

To draw on the canvas, you must use its context, typically the 2D rendering context.

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // Get 2D context

Drawing Basics on Canvas

1. Drawing Rectangles

// Draw a filled rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 100, 50);

// Draw a rectangle outline
ctx.strokeStyle = 'red';
ctx.strokeRect(150, 20, 100, 50);

// Clear a rectangle
ctx.clearRect(25, 25, 50, 25);

2. Drawing Paths (Lines and Shapes)

// Begin a new path
ctx.beginPath();
ctx.moveTo(50, 50); // Starting point
ctx.lineTo(150, 50); // Draw a line
ctx.lineTo(100, 100); // Another line
ctx.closePath(); // Close the path
ctx.strokeStyle = 'green';
ctx.stroke(); // Outline the shape

// Fill the shape
ctx.fillStyle = 'yellow';
ctx.fill();

3. Drawing Circles and Arcs

ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2); // Full circle
ctx.stroke();
ctx.fillStyle = 'purple';
ctx.fill();

4. Drawing Text

ctx.font = '20px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 50, 150); // Filled text

ctx.strokeStyle = 'blue';
ctx.strokeText('Outline Text', 50, 180); // Outlined text

Working with Images

Drawing an Image

const img = new Image();
img.src = 'example.jpg';
img.onload = () => {
  ctx.drawImage(img, 10, 10, 200, 100); // Draw the image
};

Cropping an Image

ctx.drawImage(img, 50, 50, 100, 100, 10, 10, 50, 50);

Animations on Canvas

Canvas animations are achieved by repeatedly clearing and redrawing the canvas.

Example: A Moving Ball

let x = 0;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
  ctx.beginPath();
  ctx.arc(x, 75, 20, 0, Math.PI * 2);
  ctx.fill();
  x += 2;
  if (x > canvas.width) x = 0; // Reset position
  requestAnimationFrame(animate); // Recursive call
}

animate();

Advanced Canvas Features

1. Gradients

const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'yellow');

ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);

2. Shadows

ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;

ctx.fillStyle = 'green';
ctx.fillRect(50, 50, 100, 50);

Leave a Comment