Canvas API - Web APIs | MDN (original) (raw)

Basic example

This simple example draws a green rectangle onto a canvas.

HTML

<canvas id="canvas"></canvas>

JavaScript

The Document.getElementById() method gets a reference to the HTML <canvas> element. Next, the HTMLCanvasElement.getContext() method gets that element's context—the thing onto which the drawing will be rendered.

The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

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

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 150, 100);

Result

Reference

**Note:**The interfaces related to the WebGLRenderingContext are referenced under WebGL.

CanvasCaptureMediaStreamTrack is a related interface.

Guides and tutorials

Canvas tutorial

A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.

HTML5 Canvas Deep Dive

A hands-on, book-length introduction to the Canvas API and WebGL.

Canvas Handbook

A handy reference for the Canvas API.

Manipulating video using canvas

Combining and to manipulate video data in real time.

Libraries

The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.

**Note:**See the WebGL API for 2D and 3D libraries that use WebGL.

Specifications

Specification
HTML # the-canvas-element

Browser compatibility

See also