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.
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.
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);
Store the context in a variable at setup — you will use ctx for every drawing operation throughout the program.