Using the <canvas> Element
The <canvas> HTML element allows you to render graphics using JavaScript directly in the browser. It’s suitable for games, animations, visualizations, and other dynamic content.
Basic Setup
Creating a <canvas> is simple. You define a width and height, and optionally a style such as a border.
Getting the Drawing Context
To draw on a canvas, you must first get its drawing context. Most often, this is the '2d' context, obtained using the getContext('2d') method.
Drawing a Rectangle
Use the fillRect(x, y, width, height) method to draw a rectangle. The fillStyle property sets its color.
Drawing a Line
To draw lines, use the beginPath(), moveTo(), lineTo(), and stroke() methods. These create straight lines between points.
Drawing a Circle
To draw circles, use the arc() method. Its parameters include center coordinates, radius, and start/end angles in radians.
Rendering Text
Use fillText() to render text on the canvas. The font and fillStyle properties define its appearance.
Simple Animation
To create animation, use requestAnimationFrame(). Clear the previous frame with clearRect(), then redraw. This lets you create moving objects.
✨ Ask Lara — your AI study partner
Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.
Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.

