ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

SVG & HTML5 Canvas Tutorial• 6 min read

HTML5 Canvas: Initializing the 2D Context

Canvas width/height vs CSS dimensions and understanding pixel density

The HTML5 <canvas> element provides a procedural bitmap canvas whose drawing operations are executed in JavaScript via the 2D Rendering Context.

The Critical Difference: Canvas Size vs CSS Size

Canvas Coordinate Attributes (width="800" height="600"): Sets the internal pixel resolution of the drawing buffer.

CSS Sizing (style="width: 100%"): Scales the display presentation on screen.

WARNING: If you omit width and height attributes and style via CSS only, your canvas defaults to 300x150 and stretches, causing severe pixel blurriness!

Initializing Canvas in JavaScript
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

// Set exact internal buffer dimensions
canvas.width = 600;
canvas.height = 400;

// Fill canvas with dark slate background
ctx.fillStyle = "#0f172a";
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Draw glowing cyan rectangle
ctx.fillStyle = "#06b6d4";
ctx.fillRect(50, 50, 150, 100);
Always initialize context and set explicit pixel width/height.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which method retrieves the 2D drawing API object from an HTML `<canvas>` element?