0Pricing
HTML Academy · Lesson

Setting Up the Canvas and 2D Context

Create a canvas element and acquire the 2D rendering context.

Setting Up the Canvas and 2D Context is a free HTML Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the HTML Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The canvas Element

The <canvas> element is a drawable bitmap surface in the browser:

<canvas id="myCanvas" width="800" height="400">
  <!-- Fallback for browsers without canvas support -->
  <p>Your browser does not support HTML5 Canvas.</p>
</canvas>

Width and Height Attributes

Always set canvas dimensions via HTML attributes, not CSS:

<!-- CORRECT: set intrinsic size via attributes -->
<canvas width="800" height="400"></canvas>

<!-- WRONG: CSS changes display size but not canvas resolution -->
<canvas style="width: 800px; height: 400px;"></canvas>
<!-- This stretches a default 300x150 canvas to 800x400
     Result: blurry graphics -->

Getting the 2D Context

Acquire the 2D rendering context to draw:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// ctx is a CanvasRenderingContext2D object
// All drawing operations are methods on ctx

// Check browser support:
if (!canvas.getContext) {
  console.error('Canvas not supported');
}

Coordinate System

The canvas coordinate system starts at the top-left:

// (0, 0) = top-left corner
// (width, 0) = top-right
// (0, height) = bottom-left
// (width, height) = bottom-right

// For a 800x400 canvas:
// x increases left → right (0 to 800)
// y increases top → bottom (0 to 400)
//
// Example: draw at center:
ctx.fillRect(400, 200, 10, 10);  // centered dot

Canvas State

The canvas has a drawing state that can be saved and restored:

ctx.save();       // push current state onto a stack

// Change state:
ctx.fillStyle = 'red';
ctx.globalAlpha = 0.5;

// Draw with modified state...
ctx.fillRect(100, 100, 200, 200);

ctx.restore();    // pop state: back to pre-save settings

Clearing the Canvas

Clear the entire canvas before redrawing (for animation):

// Clear entire canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);

// Or with a background color:
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);

fillStyle and strokeStyle

Set colors for fill and stroke operations:

ctx.fillStyle = 'blue';                    // CSS color name
ctx.fillStyle = '#ff6600';                 // hex color
ctx.fillStyle = 'rgb(255, 100, 0)';       // rgb
ctx.fillStyle = 'rgba(255, 100, 0, 0.5)'; // rgba with alpha
ctx.fillStyle = gradient;                  // gradient object
ctx.fillStyle = pattern;                   // pattern object

ctx.strokeStyle = '#333333';               // border color

lineWidth and Other Style Properties

Stroke and line style properties:

ctx.lineWidth = 4;           // stroke width in pixels
ctx.lineCap = 'round';       // butt | round | square
ctx.lineJoin = 'round';      // miter | round | bevel
ctx.setLineDash([5, 3]);     // dashed line: 5px dash, 3px gap
ctx.globalAlpha = 0.8;       // transparency for all drawing
ctx.globalCompositeOperation = 'multiply'; // blend modes

Responsive HiDPI Canvas

Fix blurry canvas on Retina/HiDPI displays:

function setupHiDPI(canvas, width, height) {
  const dpr = window.devicePixelRatio || 1;
  canvas.width = width * dpr;
  canvas.height = height * dpr;
  canvas.style.width = width + 'px';
  canvas.style.height = height + 'px';
  const ctx = canvas.getContext('2d');
  ctx.scale(dpr, dpr);  // scale all drawing
  return ctx;
}

Canvas vs SVG

When to choose canvas vs SVG:

  • Canvas — bitmap, pixel-by-pixel, great for games, large data visualization, image processing
  • SVG — vector, scalable, great for logos, icons, charts with interactive elements, accessibility

Canvas Accessibility

Canvas has no built-in accessibility — add manually:

<canvas
  id="chart"
  width="800"
  height="400"
  aria-label="Bar chart showing Q1-Q4 revenue growth"
  role="img"
>
  <!-- Fallback for non-canvas browsers and screen readers -->
  <table><!-- accessible data table --></table>
</canvas>

Quick Check

What is the correct way to get a canvas drawing context?

Recap: Canvas Setup

Canvas setup essentials:

  • Set width/height via HTML attributes, not CSS
  • canvas.getContext('2d') — get the drawing context
  • Top-left origin (0,0); x→right, y→down
  • ctx.save() / ctx.restore() — stack-based state management
  • Scale by devicePixelRatio for crisp Retina rendering

Frequently asked questions

Is the “Setting Up the Canvas and 2D Context” lesson free?

Yes — the full text of “Setting Up the Canvas and 2D Context” is free to read here on the web, and the HTML Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the HTML Academy course, upgrade to CoddyKit PRO.

What will I learn in “Setting Up the Canvas and 2D Context”?

Create a canvas element and acquire the 2D rendering context. You practise HTML Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start HTML Academy?

No prior experience is required. HTML Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Setting Up the Canvas and 2D Context” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this HTML Academy lesson?

Yes. Every HTML Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up the Canvas and 2D Context
  2. Drawing Rectangles and Paths
  3. Text and Images on Canvas
  4. Animation with requestAnimationFrame
← Back to HTML Academy