docs.rodeo

MDN Web Docs mirror

Canvas API

{{DefaultAPISidebar("Canvas API")}} 

The Canvas API provides a means for drawing graphics via JavaScript and the HTML {{HtmlElement("canvas")}}  element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

The Canvas API largely focuses on 2D graphics. The WebGL API, which also uses the <canvas> element, draws hardware-accelerated 2D and 3D graphics.

Basic example

This simple example draws a green rectangle onto a canvas.

HTML

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

JavaScript

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

The actual drawing is done using the {{domxref("CanvasRenderingContext2D")}}  interface. The {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}  property makes the rectangle green. The {{domxref("CanvasRenderingContext2D.fillRect()", "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

{{ EmbedLiveSample('Basic_example', 700, 180) }} 

Reference

[!NOTE] The interfaces related to the WebGLRenderingContext are referenced under WebGL.

Note: {{domxref("OffscreenCanvas")}}  is also available in web workers.

{{domxref("CanvasCaptureMediaStreamTrack")}}  is a related interface.

Guides and tutorials

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

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN