Lesson 13 of 55
HTMLCanvas Basics
9 min
Course progress24%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 13 of 55
HTML9 min
Keep these ideas in mind as you work through the lesson.
<canvas> ElementCanvas 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>
width and height attributes 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.devicePixelRatio and then scale down with CSS for crisp graphics.<noscript> or aria-label on a wrapper) if the graphic conveys essential information.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.
requestAnimationFrame? ✅Tip: Keep the drawing logic in separate functions to make the code easier to test and maintain.