HTML Canvas

The HTML <canvas> element creates a blank rectangular drawing area on your web page. JavaScript draws shapes, text, images, and animations inside it. Think of the canvas as a blank whiteboard — HTML puts the whiteboard on the page, and JavaScript hands you the marker.

What Canvas Is Used For

Canvas powers many interactive web experiences that cannot be built with regular HTML alone.

Visual Diagram — Canvas Use Cases

                [<canvas> element]
                       |
        +--------------+--------------+
        |              |              |
   Game graphics   Data charts   Image editor
   Animations      Graphs        Drawing tools
   Signatures      Infographics  Visual effects

The canvas Tag

The <canvas> tag creates the drawing area. Use the width and height attributes to set its size in pixels.

<canvas id="myCanvas" width="500" height="300">
  Your browser does not support the canvas element.
</canvas>

The text between the opening and closing tags appears only in browsers that do not support canvas — it is a fallback message. All modern browsers support canvas.

Important: Set Size in HTML, Not CSS

Always set width and height as HTML attributes on the canvas tag. If you set them only in CSS, the drawing inside scales and blurs because the canvas drawing buffer stays at its default 300×150 pixel size.

<!-- Correct -->
<canvas id="c" width="600" height="400"></canvas>

<!-- Wrong — drawing will look blurry -->
<canvas id="c" style="width:600px; height:400px;"></canvas>

Getting the Drawing Context

Before you can draw, JavaScript must get access to the canvas drawing context. The 2D context provides all the drawing methods.

<canvas id="myCanvas" width="500" height="300"></canvas>

<script>
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");
</script>

The variable ctx is the drawing tool. Everything you draw goes through ctx.

Drawing Rectangles

Canvas provides three built-in rectangle methods.

Visual Diagram — Rectangle Methods

Canvas coordinate system:
(0,0) ────────── x increases →
  |
  | y increases ↓
  |
  ↓

fillRect draws a filled rectangle:
  ctx.fillRect(x, y, width, height)
  ctx.fillRect(50, 50, 200, 100)

  x=50, y=50 is the top-left corner
  width=200, height=100 is the size

  +----(50,50)
  |              |
  |   200 wide   |  100 tall
  |              |
  +---(250,150)---+
<script>
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");

  // Filled blue rectangle
  ctx.fillStyle = "blue";
  ctx.fillRect(50, 50, 200, 100);

  // Rectangle outline only (no fill)
  ctx.strokeStyle = "red";
  ctx.lineWidth = 3;
  ctx.strokeRect(100, 200, 150, 70);

  // Erase a rectangular area
  ctx.clearRect(80, 70, 60, 40);
</script>

Drawing Lines and Paths

Lines and shapes use the path drawing system. You begin a path, move to a starting point, draw to other points, and then stroke or fill the result.

<script>
  ctx.beginPath();          // start a new path
  ctx.moveTo(50, 50);       // lift the pen and move to (50,50)
  ctx.lineTo(200, 50);      // draw line to (200,50)
  ctx.lineTo(200, 150);     // draw line to (200,150)
  ctx.closePath();          // draw line back to starting point
  ctx.strokeStyle = "black";
  ctx.stroke();             // render the lines
</script>

Visual Diagram — Path Drawing

moveTo(50,50) → sets pen position, no line drawn

lineTo(200,50):
(50,50)──────────────(200,50)

lineTo(200,150):
(50,50)──────────────(200,50)
                          |
                      (200,150)

closePath():
(50,50)──────────────(200,50)
   \                      |
    \                 (200,150)
     ↖__________________/
      line back to start

Drawing Circles and Arcs

The arc() method draws circles and curved sections. The angle is measured in radians — a full circle is 2π radians (approximately 6.28).

ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.stroke();

Full Circle Example

<script>
  ctx.beginPath();
  ctx.arc(200, 150, 80, 0, 2 * Math.PI);   // full circle
  ctx.fillStyle = "orange";
  ctx.fill();
  ctx.strokeStyle = "black";
  ctx.lineWidth = 2;
  ctx.stroke();
</script>

Visual Diagram — arc() Parameters

ctx.arc(200, 150, 80, 0, 2*Math.PI)
          ^    ^   ^   ^      ^
          cx   cy  r  start  end angle

Full circle:  start=0, end=2*Math.PI  (full 360°)
Half circle:  start=0, end=Math.PI   (180°)
Quarter:      start=0, end=Math.PI/2 (90°)

Writing Text on Canvas

Use fillText() to draw filled text and strokeText() to draw text outlines.

<script>
  ctx.font = "30px Arial";
  ctx.fillStyle = "black";
  ctx.fillText("Hello Canvas!", 50, 80);    // filled text

  ctx.font = "bold 24px Georgia";
  ctx.strokeStyle = "navy";
  ctx.strokeText("Outlined Text", 50, 140);  // outlined text
</script>

Drawing Images on Canvas

Canvas can draw any image onto itself using drawImage().

<script>
  const img = new Image();
  img.src = "photo.jpg";
  img.onload = function() {
    ctx.drawImage(img, 50, 50);               // draw at original size
    ctx.drawImage(img, 50, 50, 200, 150);     // draw at 200x150 pixels
  };
</script>

The image must fully load before drawing. The onload function waits for the image to be ready and then draws it.

Canvas Coordinate System

Visual Diagram — How Canvas Coordinates Work

(0,0) is the TOP-LEFT corner of the canvas

       0   100  200  300  400  500
  0    +----+----+----+----+----+
       |                        |
  100  |                        |
       |      (200,150)         |
  150  |          *             |
       |                        |
  300  |                        |
       +----+----+----+----+----+

x increases going RIGHT
y increases going DOWN (opposite of math class!)

Saving and Restoring Canvas State

Canvas keeps a stack of drawing states. save() pushes the current state onto the stack. restore() pops it back. This lets you apply styles temporarily without affecting the rest of your drawing.

<script>
  ctx.fillStyle = "blue";

  ctx.save();                   // save current state (blue fill)
    ctx.fillStyle = "red";
    ctx.fillRect(50, 50, 100, 100);   // draws red rectangle
  ctx.restore();                // restore: fill is blue again

  ctx.fillRect(200, 50, 100, 100);    // draws blue rectangle
</script>

Simple Animation with Canvas

Canvas animation works by clearing the canvas and redrawing everything many times per second. The requestAnimationFrame() function calls your drawing function before each screen refresh.

<script>
  let x = 0;

  function animate() {
    ctx.clearRect(0, 0, 500, 300);   // clear the canvas
    ctx.fillStyle = "green";
    ctx.fillRect(x, 100, 50, 50);   // draw square at new position
    x += 2;                          // move 2 pixels right
    if (x > 500) x = 0;             // reset when off screen
    requestAnimationFrame(animate);  // call again on next frame
  }

  animate();
</script>

This creates a green square that slides from left to right and loops back. The same principle powers all canvas-based games and animations.

Canvas vs SVG

Feature         Canvas                     SVG
-----------     ------------------------   -----------------------
Rendering       Pixel-based (bitmap)       Vector (mathematical)
Performance     Fast for many objects      Better for few objects
Scalability     Blurs when enlarged        Stays sharp at any size
Interaction     Handle events via pixels   Each element is a DOM node
Best for        Games, animations          Icons, charts, diagrams

Use canvas when you draw many objects or need pixel-level control. Use SVG when you need shapes that stay sharp at any zoom level and when individual elements need click events.

Leave a Comment

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