SyntaxStudy
Sign Up
HTML Beginner 1 min read

HTML Canvas

HTML Canvas

The <canvas> element is a blank drawing area. You draw on it using JavaScript. It is used for games, data visualisations, animations, and image editing.

How It Works

  1. Add a <canvas> element with a width and height
  2. Get the 2D rendering context with JavaScript
  3. Call drawing methods on the context

Common Drawing Methods

  • fillRect(x, y, w, h) — Filled rectangle
  • strokeRect(x, y, w, h) — Rectangle outline
  • fillText(text, x, y) — Text
  • beginPath() / arc() / fill() — Circles
Example
<canvas id="myCanvas" width="400" height="200"
  style="border: 1px solid #ddd;"></canvas>

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

  // Blue rectangle
  ctx.fillStyle = "royalblue";
  ctx.fillRect(20, 20, 150, 80);

  // Red circle
  ctx.fillStyle = "crimson";
  ctx.beginPath();
  ctx.arc(280, 100, 60, 0, Math.PI * 2);
  ctx.fill();

  // Text
  ctx.fillStyle = "white";
  ctx.font = "18px Arial";
  ctx.fillText("Canvas!", 60, 65);
</script>