Loading...

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.

Track Your Progress 🚀

Learn more easily by tracking your progress completely for free.


Top tools

CodeHubBoardly NEWLinksy NEWChromo NEW

Select Language

Set theme

© 2025 ReadyTools. All rights reserved.