bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/HTML/Reference and Practice
HTML•Reference and Practice

HTML Canvas Reference

Concept visual

HTML Canvas Reference

Graph traversalgraph
ABCDE
current
queued
1
4

Start from A

The

<canvas> element defines a bitmapped area in an HTML page.

The

Canvas API

allows JavaScript to draw graphics on the canvas. The Canvas API can draw shapes, lines, curves, boxes, text, and images, with colors, rotations, transparencies, and other pixel manipulations. You can add a canvas element anywhere in an HTML page with the <canvas> tag:

Example

<canvas id="myCanvas" width="300" height="150"></canvas>

You can access a

<canvas> element with the HTML DOM method getElementById(). To draw in the canvas you need to create a 2D context object:

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

Note

The HTML

<canvas> element itself has no drawing abilities. You must use JavaScript to draw any graphics.

The getContext()

method returns an object with tools (methods) for drawing.

Drawing on the Canvas

After you have created a 2D context, you can draw on the canvas.

The fillRect()

Formula

method draws a black rectangle with a top - left corner at position 20,20.

The rectangle is 150 pixel wide and 100 pixels high.

Example

const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");
ctx.fillRect(20, 20, 150, 100);

Using Colors

The fillStyle property sets the fill color of the drawing object:

Example

const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);

You can also create a new

<canvas> element with the document.createElement() method, and add the element to an existing HTML page:

Example

const myCanvas = document.createElement("canvas");
document.body.appendChild(myCanvas);
const ctx = myCanvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);

Paths

The common way to draw on the canvas is to:

Formula

Begin a Path - beginPath()
Move to a Point - moveTo()
Draw in the Path - lineTo()
Draw the Path - stroke()

Example

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke();

Complete Canvas API Reference

This reference covers all Properties and Methods of the getContext("2d") Object, used to draw text, lines, boxes, circles, pictures, and more on the canvas.

Drawing Methods

There are only 3 methods to draw directly on the canvas:

Method

Description fillRect()

Draws a "filled" rectangle strokeRect() Draws a rectangle (with no fill) clearRect()

Clears specified pixels within a rectangle

Path Methods

Method

Previous

HTML Syllabus

Next

HTML Study Plan