Canvas Rendering Lesson

Canvas rendering means drawing graphics onto an HTML canvas with JavaScript. The canvas gives the program a drawing surface, and the rendering context provides commands for shapes, colors, images, and text.

Short Example

Code Runner Challenge

Canvas Rendering Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Canvas Rendering Lesson

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "skyblue";
ctx.fillRect(20, 30, 100, 60);
ctx.fillStyle = "black";
ctx.fillText("Player", 35, 65);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Canvas drawings do not behave like normal HTML elements. If something moves, the program usually clears the canvas and redraws the whole scene in the new positions.

This makes canvas useful for games and animations because the program has direct control over each frame. The drawing code decides exactly what appears and where it appears.