JavaScript Academy · Lesson

Setting Up the Canvas Context

Get and configure the 2D rendering context.

Lesson 1 of 413 steps

Setting Up the Canvas Context is a free JavaScript Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 4 lessons in total.

What Is the Canvas API?

The Canvas API lets you draw 2D graphics with JavaScript onto a <canvas> element. You get a drawing surface made of pixels and a set of commands to paint shapes, images, and text.

  • The markup is a single <canvas> tag.
  • All drawing happens in JavaScript through a context object.
<canvas id="board" width="320" height="200"></canvas>

Getting the Context

Call getContext('2d') on the canvas element to get a CanvasRenderingContext2D. Every drawing command goes through this object.

const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");
console.log(ctx.constructor.name); // CanvasRenderingContext2D

The Coordinate System

The origin (0, 0) is the top-left corner. X grows to the right, Y grows downward. A 320x200 canvas has its bottom-right corner at (320, 200).

Width and Height Attributes

The width and height HTML attributes set the drawing buffer size in pixels. They default to 300x150 if omitted. Setting them in JS also clears the canvas.

const canvas = document.getElementById("board");
canvas.width = 400;
canvas.height = 300;
console.log(canvas.width, canvas.height); // 400 300

CSS Size vs Buffer Size

CSS width/height stretch the canvas on screen but do NOT change the pixel buffer. If they differ from the attributes, drawings look blurry or stretched. Keep them in sync for crisp output.

canvas.width = 400;  // buffer pixels
canvas.style.width = "400px"; // display size — match it

Handling High-DPI Screens

On Retina displays devicePixelRatio is often 2. Scale the buffer up and the context down so lines stay sharp.

const dpr = window.devicePixelRatio || 1;
canvas.width = 400 * dpr;
canvas.height = 300 * dpr;
canvas.style.width = "400px";
canvas.style.height = "300px";
ctx.scale(dpr, dpr);

Setting Fill and Stroke Styles

Drawing state lives on the context. fillStyle sets the fill color, strokeStyle sets the outline color. They accept any CSS color string.

ctx.fillStyle = "#3498db";
ctx.strokeStyle = "rgba(231, 76, 60, 0.8)";
ctx.lineWidth = 4;

Your First Drawing

With the context ready you can paint immediately. fillRect(x, y, w, h) paints a filled rectangle using the current fillStyle.

const ctx = document.getElementById("board").getContext("2d");
ctx.fillStyle = "tomato";
ctx.fillRect(20, 20, 150, 80);

Clearing the Canvas

clearRect(x, y, w, h) erases a rectangular region back to transparent. Clearing the whole buffer is the usual first step of each animation frame.

ctx.clearRect(0, 0, canvas.width, canvas.height);

Saving and Restoring State

save() pushes the current style/transform onto a stack; restore() pops it back. This isolates temporary changes.

ctx.save();
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 50);
ctx.restore(); // fillStyle reverts to previous value

Feature Detection

Guard against very old browsers by checking getContext exists before using it.

const canvas = document.getElementById("board");
if (canvas.getContext) {
  const ctx = canvas.getContext("2d");
  // safe to draw
} else {
  console.log("Canvas not supported");
}

Quick Check

Test your understanding of canvas setup.

Recap: Canvas Setup

You learned to: grab the canvas, call getContext('2d'), understand the top-left origin, set buffer vs CSS size, handle high-DPI with devicePixelRatio, and configure fillStyle/strokeStyle. Next: drawing shapes and paths.

Free to start

Learn JavaScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
59
Lessons
200

Frequently Asked Questions

Is the “Setting Up the Canvas Context” lesson free?

Yes — any 3 lessons of the JavaScript Academy learning path, including “Setting Up the Canvas Context”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 4 lessons in total.

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

Get and configure the 2D rendering context. You practise JavaScript 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 JavaScript Academy?

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

How long does the “Setting Up the Canvas 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 JavaScript Academy lesson?

Yes. Every JavaScript 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 Context
  2. Drawing Shapes and Paths
  3. Working with Images and Text
  4. Animation with requestAnimationFrame
← Back to JavaScript Academy