The Canvas API provides a means for drawing graphics via JavaScript and the HTML <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.
The <canvas> element is just a bitmap and does not provide information about any drawn objects. Text written on canvas can cause legibility issues with users relying on screen magnification. The pixels within a canvas element do not scale and can become blurry with magnification. This is because they are not a vector but letter-shaped collection of pixels. When zooming in on it, the pixels become bigger.
Canvas content is not exposed to accessibility tools like semantic HTML is. In general, you should use canvases like images and avoid using them to render significant content without accessible backing markup.
This simple example draws a green rectangle onto a canvas.
<canvas id="canvas"></canvas>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);HTMLCanvasElementCanvasRenderingContext2DCanvasGradientCanvasPatternImageBitmapImageDataTextMetricsOffscreenCanvasPath2D ImageBitmapRenderingContext Note: The interfaces related to the WebGLRenderingContext are referenced under WebGL.
Note: OffscreenCanvas is also available in web workers.
CanvasCaptureMediaStreamTrack is a related interface.
A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.
A hands-on, book-length introduction to the Canvas API and WebGL.
A handy reference for the Canvas API.
Combining <video> and <canvas> to manipulate video data in real time.
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.