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:
| Parameter | Type | Description |
|---|---|---|
| getContext("2d") | Method | Returns CanvasRenderingContext2D object for 2D drawing. |
Ready-to-Run Code Example
Executable in CompilraRun 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
HTML5 Semantic Structural Boilerplate and Metadata Configurations
Structure HTML5 documents with semantic boilerplate tags (<!DOCTYPE html>, <meta>, <header>, <main>, <nav>, <footer>) and responsive viewport configurations.
DOM Manipulation: querySelector, textContent, and innerHTML
Select and manipulate HTML elements using document.querySelector and textContent.
HTML Inline Interactive Custom Logic: Script Injection Nodes and DOM Event Embeds
Embed interactive custom execution logic inside HTML documents using script injection nodes (<script>), DOM event listeners, and dynamic DOM mutation methods.
HTML Online Compiler
Open in Compilra IDE
Run and test HTML on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.