SyntaxStudy
Sign Up
HTML Introduction to HTML Canvas
HTML Beginner 4 min read

Introduction to HTML Canvas

HTML Canvas

The <canvas> element provides a rectangular drawing surface for 2D graphics rendered with JavaScript. It is pixel-based and immediate-mode — you draw and the pixels are fixed.

Canvas is ideal for games, image editing, data visualization, and animations.

Example
<!-- Canvas element with fallback -->
<canvas id="myCanvas" width="600" height="400">
  Your browser does not support canvas.
</canvas>

<script>
  const canvas = document.getElementById("myCanvas");
  if (canvas.getContext) {
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#4CAF50";
    ctx.fillRect(50, 50, 200, 100);
  }
</script>
Pro Tip

Set canvas width and height as HTML attributes, not CSS — CSS sizing distorts the drawing surface.