⚡IntermediateAdvanced Media
Canvas Element Basics
Draw shapes, text, and images programmatically with the HTML5 <canvas> element.
Overview
The <canvas> element provides a 2D drawing surface that you control entirely with JavaScript. Unlike SVG, canvas is raster-based (pixel-level) and does not retain a DOM tree of drawn objects once drawn, pixels are just pixels.
Canvas excels at: dynamic charts and graphs, game graphics, image editing, particle effects, real-time data visualization, and signature/drawing pads.
The drawing API is accessed via getContext('2d'). The coordinate origin (0,0) is the top-left corner; x increases rightward and y increases downward.
Key Points
- •<canvas> requires width and height attributes; default is 300×150 pixels
- •The canvas is blank/transparent until you draw on it with JavaScript
- •ctx = canvas.getContext("2d") returns the 2D rendering context
- •ctx.fillRect(x, y, w, h) fills a rectangle; ctx.strokeRect for outline only
- •ctx.beginPath() + ctx.arc() + ctx.fill() draws a circle
- •Always provide fallback content between <canvas> tags for accessibility
Examples
Drawing basic shapes
<canvas id="myCanvas" width="400" height="200">
Canvas is not supported in your browser.
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Blue filled rectangle
ctx.fillStyle = '#3b82f6';
ctx.fillRect(20, 20, 120, 80);
// Red stroked rectangle
ctx.strokeStyle = '#ef4444';
ctx.lineWidth = 3;
ctx.strokeRect(160, 20, 120, 80);
// Green circle
ctx.fillStyle = '#22c55e';
ctx.beginPath();
ctx.arc(340, 60, 40, 0, Math.PI * 2);
ctx.fill();
</script>Drawing text and lines
const ctx = canvas.getContext('2d');
// Text
ctx.font = 'bold 24px sans-serif';
ctx.fillStyle = '#111827';
ctx.textAlign = 'center';
ctx.fillText('Hello Canvas!', canvas.width / 2, 50);
// Line
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(350, 100);
ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 2;
ctx.stroke();
// Triangle path
ctx.beginPath();
ctx.moveTo(200, 120);
ctx.lineTo(150, 180);
ctx.lineTo(250, 180);
ctx.closePath();
ctx.fillStyle = '#f59e0b';
ctx.fill();Drawing an image onto canvas
const img = new Image();
img.src = 'photo.jpg';
img.onload = () => {
ctx.drawImage(img, 0, 0); // original size
ctx.drawImage(img, 0, 0, 200, 150); // scaled
ctx.drawImage(img, 10, 10, 100, 100, // source clip
0, 0, 200, 200); // destination
};Images must be loaded (onload) before drawing to canvas.
Common Mistakes
- Setting canvas size via CSS instead of width/height attributes stretches the canvas, distorting drawings
- Forgetting ctx.beginPath() before drawing a new shape paths accumulate from previous calls
- Not providing fallback content inside <canvas> for screen readers or unsupported browsers
Note
Use canvas for pixel-level, highly dynamic, or game-like rendering. Use SVG for scalable, accessible, interactive vector graphics. For charts, consider a library like Chart.js (canvas-based) or D3.js (SVG-based) rather than raw canvas.
Exercises
Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4