SyntaxStudy
Sign Up
HTML Getting the 2D Rendering Context
HTML Beginner 4 min read

Getting the 2D Rendering Context

Canvas Rendering Context

All drawing is done through the rendering context, obtained with getContext("2d"). This object provides every drawing method and style property.

For 3D graphics, use getContext("webgl") instead.

Example
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// The context object has all drawing methods
console.log(typeof ctx.fillRect);   // "function"
console.log(typeof ctx.strokeText); // "function"

// Canvas dimensions via the element
console.log(canvas.width, canvas.height);

// Clear the entire canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
Pro Tip

Store the context in a variable at setup — you will use ctx for every drawing operation throughout the program.