learn2kode.in

JavaScript Canvas API

What Is the JavaScript Canvas API?

The JavaScript Canvas API is a powerful HTML5 Web API that allows developers to draw graphics, shapes, text, images, and animations directly on a web page using JavaScript.
Instead of using HTML elements for visuals, the Canvas API provides a pixel-based drawing surface, making it ideal for games, charts, image editors, visualizations, and animations.
How Canvas Works
The Canvas API works with the <canvas> HTML element. JavaScript controls everything that appears inside the canvas.

Basic Canvas Structure

<canvas id="myCanvas" width="400" height="300"></canvas>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

Drawing Shapes Using Canvas API

Draw a Rectangle
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);
Draw an Outline Rectangle
ctx.strokeStyle = "red";
ctx.strokeRect(50, 50, 150, 100);
Drawing Lines & Paths
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.stroke();
Paths allow you to create complex shapes and drawings.

Drawing Text on Canvas

Fill Text
ctx.font = "20px Arial";
ctx.fillText("Hello Canvas!", 50, 50);
Stroke Text
ctx.strokeText("Outlined Text", 50, 80);
Canvas text is commonly used in games, dashboards, and data visualizations.

Drawing Images on Canvas

const img = new Image();
img.src = "image.jpg";
img.onload = () => {
  ctx.drawImage(img, 50, 50, 200, 150);
};
This feature makes Canvas ideal for image editing apps and dynamic graphics.

Canvas Animations with JavaScript

Animations are created using requestAnimationFrame().
let x = 0;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(x, 50, 50, 50);
  x += 2;
  requestAnimationFrame(animate);
}

animate();
This technique is widely used in HTML5 games and interactive UI effects.

Common Use Cases of Canvas API

Canvas API vs SVG (Quick Insight)

Key Advantages of JavaScript Canvas API