JavaScript Canvas API Basics

The Canvas API lets JavaScript draw graphics — shapes, lines, text, and images — directly onto an HTML page using the <canvas> element. Think of it as a blank whiteboard inside your webpage where JavaScript holds the marker. You can draw anything: charts, games, animations, custom illustrations, or image editing tools.

Setting Up a Canvas

Add the <canvas> element to your HTML and give it a width and height in pixels.

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

Then get the drawing context in JavaScript. The "2d" context gives you a 2D drawing API.

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");

Diagram: Canvas Coordinate System

(0,0) ─────────────────────► X axis (width)
  │
  │    Canvas area (600 × 400)
  │
  │
  ▼
Y axis (height)

Top-left corner = (0, 0)
Bottom-right corner = (600, 400)
X increases to the right
Y increases downward

Drawing Rectangles

Filled Rectangle

ctx.fillStyle = "blue";           // set fill color
ctx.fillRect(50, 50, 200, 100);  // x, y, width, height

Outlined Rectangle (Stroke)

ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctx.strokeRect(300, 50, 200, 100); // x, y, width, height

Clear a Rectangle

ctx.clearRect(0, 0, canvas.width, canvas.height); // clears the whole canvas

Diagram: Three Rectangle Operations

fillRect(50,50,200,100):
  ■■■■■■■■■■■■■■■■■■■■  ← solid blue rectangle at (50,50)

strokeRect(300,50,200,100):
  □□□□□□□□□□□□□□□□□□□□  ← red outline rectangle at (300,50)

clearRect(0,0,600,400):
  (everything erased)

Drawing Lines

Lines use a path system: begin the path, move to a starting point, draw to an ending point, then stroke the path.

ctx.beginPath();           // start a new path
ctx.moveTo(50, 200);      // lift pen, move to start point
ctx.lineTo(550, 200);     // draw line to end point
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.stroke();             // actually draw it

Drawing a Triangle

ctx.beginPath();
ctx.moveTo(300, 50);   // top point
ctx.lineTo(100, 350);  // bottom-left
ctx.lineTo(500, 350);  // bottom-right
ctx.closePath();       // connect back to start
ctx.fillStyle = "orange";
ctx.fill();
ctx.strokeStyle = "black";
ctx.stroke();

Diagram: Triangle Path

          (300,50)
             ▲
            / \
           /   \
          /     \
(100,350)────────(500,350)

moveTo(300,50) → start at top
lineTo(100,350) → draw to bottom-left
lineTo(500,350) → draw to bottom-right
closePath() → connect back to (300,50)

Drawing Circles (Arc)

Use arc(x, y, radius, startAngle, endAngle). Angles are in radians. A full circle goes from 0 to 2 * Math.PI.

ctx.beginPath();
ctx.arc(300, 200, 80, 0, 2 * Math.PI); // center at (300,200), radius 80
ctx.fillStyle = "purple";
ctx.fill();

Semi-Circle

ctx.beginPath();
ctx.arc(300, 200, 80, 0, Math.PI); // 0 to π = half circle (bottom half)
ctx.stroke();

Diagram: Arc Angles

        0 (right)
           │
  3π/2  ───┼───  π/2
 (top)     │    (bottom in canvas coords)
           │
          π (left)

Full circle: 0 → 2π
Top half:    π → 2π (or 0)
Bottom half: 0 → π

Drawing Text

ctx.font = "36px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello, Canvas!", 100, 100);  // text, x, y

// Outlined text
ctx.strokeStyle = "blue";
ctx.strokeText("Outlined Text", 100, 200);

Text Alignment

ctx.textAlign = "center";       // "left", "center", "right"
ctx.textBaseline = "middle";    // "top", "middle", "bottom"
ctx.fillText("Centered", canvas.width / 2, canvas.height / 2);

Colors and Gradients

Solid Color

ctx.fillStyle = "#FF6B6B";     // hex color
ctx.fillStyle = "rgb(100,200,50)"; // RGB
ctx.fillStyle = "rgba(0,0,255,0.5)"; // semi-transparent blue

Linear Gradient

let gradient = ctx.createLinearGradient(0, 0, 600, 0); // left to right
gradient.addColorStop(0, "blue");
gradient.addColorStop(1, "red");

ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 600, 100);

Diagram: Linear Gradient

Left (0)     ──────────────────────►  Right (600)
 Blue  ░░░░░░░░░░░░░░░░░░░░░░░░░░░░  Red

Mini Project: Simple Bar Chart

let data   = [80, 120, 60, 150, 90];
let labels = ["Jan", "Feb", "Mar", "Apr", "May"];
let colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7"];

let barWidth = 80;
let gap      = 30;
let baseY    = 350;

data.forEach(function(value, index) {
  let x = 50 + index * (barWidth + gap);

  // Draw bar
  ctx.fillStyle = colors[index];
  ctx.fillRect(x, baseY - value, barWidth, value);

  // Draw label
  ctx.fillStyle = "black";
  ctx.font = "14px Arial";
  ctx.textAlign = "center";
  ctx.fillText(labels[index], x + barWidth / 2, baseY + 20);

  // Draw value
  ctx.fillText(value, x + barWidth / 2, baseY - value - 5);
});

Diagram: Bar Chart Layout

 150        ┌──────┐
 120  ┌──────┐       ┌──────┐
  90  │      │       │      │ ┌──────┐
  80 ┌┤      │       │      │ │      │
  60 ││      │ ┌─┐   │      │ │      │
     ││      │ │ │   │      │ │      │
─────┘└──────┘ └─┘   └──────┘ └──────┘
     Jan    Feb  Mar   Apr    May

Saving the Canvas as an Image

let imageUrl = canvas.toDataURL("image/png");
let link = document.createElement("a");
link.href = imageUrl;
link.download = "drawing.png";
link.click();

What Canvas Is Used For

Use CaseExample
Data visualizationBar charts, pie charts, line graphs
Browser games2D platformers, puzzle games
Image manipulationCropping, filters, photo editors
AnimationsParticle effects, loading animations
Signature padsDigital sign-here fields

Summary

The Canvas API turns the <canvas> element into a drawing board controlled by JavaScript. Get a 2D context with getContext("2d"), then use methods like fillRect, arc, beginPath, and fillText to draw shapes, circles, lines, and text. Combine colors, gradients, and data to build charts, games, or image tools entirely in the browser without any external libraries.

Leave a Comment

Your email address will not be published. Required fields are marked *