The HTML <canvas> element provides a bitmapped pixel surface for rendering dynamic 2D graphics, charts, image manipulations, and game animations using JavaScript drawing APIs.
The <canvas> tag serves as a blank visual canvas container. All actual drawing is controlled via JavaScript:
<!-- Declare canvas dimensions -->
<canvas id="gameCanvas" width="600" height="400">
Your browser does not support the HTML canvas element.
</canvas>
// Access 2D drawing context in JavaScript
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Draw a filled rectangle
ctx.fillStyle = "#38bdf8";
ctx.fillRect(20, 20, 150, 100);
Key canvas API concepts:
width and height attributes directly on the <canvas> tag rather than CSS to prevent image pixel stretching.getContext('2d')): Obtains the drawing API object containing methods for shapes, paths, text, images, and gradients.<canvas>...</canvas> displays only if the user's browser lacks canvas support.flowchart TD
A["HTML <canvas id='myCanvas'>"] --> B["JS: canvas.getContext('2d')"]
B --> C["Set Fill / Stroke Styles (ctx.fillStyle = '#38bdf8')"]
C --> D["Execute Drawing Operations (fillRect, fillText, drawImage)"]
D --> E["Render Bitmapped Pixel Output"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Canvas Demonstration</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>Interactive 2D Canvas Graphics</h2>
<div style="background-color: #1e293b; padding: 1rem; border-radius: 8px; display: inline-block;">
<canvas id="demoCanvas" width="400" height="200" style="border: 1px solid #334155; border-radius: 4px; display: block;"></canvas>
</div>
<script>
const canvas = document.getElementById("demoCanvas");
const ctx = canvas.getContext("2d");
// Draw background rectangle
ctx.fillStyle = "#0f172a";
ctx.fillRect(0, 0, 400, 200);
// Draw glowing circle
ctx.beginPath();
ctx.arc(200, 100, 60, 0, Math.PI * 2);
ctx.fillStyle = "#38bdf8";
ctx.fill();
// Add text over canvas
ctx.font = "16px sans-serif";
ctx.fillStyle = "#ffffff";
ctx.textAlign = "center";
ctx.fillText("HTML5 Canvas 2D", 200, 105);
</script>
</body>
</html>
width and height as HTML attributes: Avoid scaling canvas width via CSS width: 100% without setting internal canvas coordinate dimensions, as CSS scaling distorts graphics ratio.ctx.clearRect(0, 0, width, height) at the start of every animation loop frame before redrawing objects.Create a <canvas> element with width="300" and height="150", and write a script drawing a green rectangle (#059669) inside it!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.