Skip to content
HTML5

Canvas Basics

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

#canvas#graphics

Code

html5
<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>