Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Canvas Basics | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 13 of 55

·HTML

Canvas Basics

9 min

Course progress24%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Canvas element attributes (`width`, `height`) and their importance
  • Obtaining the 2D rendering context with `getContext('2d')`
  • Basic drawing commands (`fillRect`, `stroke`, `clearRect`)
  • High‑DPI handling for crisp graphics
  • Accessibility considerations and fallback strategies
  • 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

    • 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.
    • For high‑DPI displays, multiply the canvas size by devicePixelRatio and then scale down with CSS for crisp graphics.
    • Canvas is not accessible by default; provide a fallback description (<noscript> or aria-label on 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

    1. Width & height set via attributes, not CSS? ✅
    2. High‑DPI scaling handled when needed? ✅
    3. Fallback description for essential graphics? ✅
    4. Animation loop uses requestAnimationFrame? ✅
    5. No inline scripts that break CSP? ✅

    Tip: Keep the drawing logic in separate functions to make the code easier to test and maintain.

    Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
    Previous lessonSetting Up Your Development EnvironmentContinue to lesson 14Canvas 2D API – Shapes and PathsBack to HTML Course curriculum