Lesson 13 of 55 · HTML
Canvas Basics
Duration: 9 min
The <canvas> Element
Canvas provides a pixel‑based drawing surface controlled entirely by JavaScript.
<canvas id='myCanvas' width='300' height='150' style='border:1px solid #000;'></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#ff0000';
ctx.fillRect(20, 20, 100, 50); // red rectangle
</script>
Core concepts
widthandheightattributes set the drawing buffer size (in CSS pixels). Changing them via CSS only scales the canvas.getContext('2d')returns the rendering context used for drawing commands.- For high‑DPI displays, multiply the canvas size by
devicePixelRatioand then scale down with CSS for crisp graphics. - Canvas is not accessible by default; provide a fallback description (
<noscript>oraria-labelon a wrapper) if the graphic conveys essential information.
Animation basics
function draw(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw something based on timestamp
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
requestAnimationFrame synchronises drawing with the browser’s refresh rate and is more performant than setTimeout.
Quick checklist for canvas
- Width & height set via attributes, not CSS? ✅
- High‑DPI scaling handled when needed? ✅
- Fallback description for essential graphics? ✅
- Animation loop uses
requestAnimationFrame? ✅ - No inline scripts that break CSP? ✅
Tip: Keep the drawing logic in separate functions to make the code easier to test and maintain.