HTML:HTML5 Canvas API: 2D Drawing and Animations
HTML•Canvas 2D

HTML5 Canvas API: 2D Drawing and Animations

Learn the Canvas 2D context API: drawing rectangles, paths, circles, and rendering graphics in real time.

Syntax

const ctx = canvas.getContext("2d"); ctx.fillRect(x, y, w, h);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
getContext("2d")MethodReturns CanvasRenderingContext2D object for 2D drawing.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing HTML locally:

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; padding: 20px; text-align: center; }
    canvas { border: 2px solid #0f172a; border-radius: 8px; background: #0f172a; }
  </style>
</head>
<body>
  <h2>HTML5 2D Canvas Graphics</h2>
  <canvas id="myCanvas" width="300" height="150"></canvas>

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

    // Draw background gradient rectangle
    ctx.fillStyle = "#3b82f6";
    ctx.fillRect(30, 30, 90, 90);

    // Draw circle
    ctx.beginPath();
    ctx.arc(200, 75, 45, 0, Math.PI * 2);
    ctx.fillStyle = "#10b981"; // Emerald green
    ctx.fill();

    // Render text
    ctx.fillStyle = "#ffffff";
    ctx.font = "14px sans-serif";
    ctx.fillText("Compilra 2D", 40, 80);
  </script>
</body>
</html>
Expected Output:
[Rendered HTML5 2D Canvas: Dark Viewport with Blue Rectangle, Green Circle, and White Text Label]

How It Works: Step-by-Step

  • Lines 15-16: Gets 2D rendering context from canvas.
  • Lines 18-29: Draws rectangle, arc path (circle), and text overlay.

Key Concepts

  • The Canvas element provides pixel-level immediate-mode rendering.
  • Always set canvas width and height attributes directly (not through CSS width/height) to avoid distortion.

Common Mistake: Setting canvas dimensions via CSS instead of width/height attributes

CSS width/height stretches the default 300x150 pixel canvas, resulting in blurry graphics.

❌ Incorrect
<canvas style="width: 600px; height: 300px;"></canvas> // Stretched & blurry!
✅ Correct
<canvas width="600" height="300"></canvas>

Related HTML Tutorials & Compiler

Run and test HTML on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

HTML Online Compiler