Skip to content
","url":"https://ez4code.com/snippets/html5-canvas-basics","keywords":"canvas, graphics","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
HTML5

Canvas Basics

Draw shapes, lines, and text on a 2D canvas.

By EZ4Code Team
canvasgraphics

Code

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

  // Rectangle
  ctx.fillStyle = "#1976d2";
  ctx.fillRect(10, 10, 100, 50);

  // Line
  ctx.beginPath();
  ctx.moveTo(20, 100);
  ctx.lineTo(200, 150);
  ctx.strokeStyle = "red";
  ctx.stroke();

  // Circle
  ctx.beginPath();
  ctx.arc(220, 80, 40, 0, Math.PI * 2);
  ctx.fillStyle = "green";
  ctx.fill();

  // Text
  ctx.font = "16px sans-serif";
  ctx.fillText("Hello Canvas", 50, 180);
</script>

Explanation

The canvas element provides a scriptable bitmap drawing surface via a 2D context. fillRect, arc, and fillText draw shapes and text, while beginPath groups connected drawing commands. Canvas is ideal for games and charts but is resolution-dependent and not vector-based like SVG.

More HTML5 Snippets