--- title: Canvas API slug: Web/API/Canvas_API translation_of: Web/API/Canvas_API ---
{{CanvasSidebar}}

Canvas API cung cấp phương tiện để vẽ đồ họa thông qua JavaScript và HTML {{HtmlElement("canvas")}} thuộc tính. Nó có thể được sử dụng cho hình động, đồ họa game, trực quan hóa dữ liệu, xử lí ảnh và video trong thời gian thực.

Canvas API tập trung vào đồ họa 2D. WebGL API, nó cũng sử dụng <canvas> , để vẽ đồ họa 2D và 3D.

Ví dụ đơn giản

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.

{{domxref("CanvasCaptureMediaStream")}} 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.
Demo: A basic ray-caster
A demo of ray-tracing animation using canvas.
Manipulating video using canvas
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} 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 libaries that use WebGL.

Specifications

Specification Status Comment
{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}} {{Spec2('HTML WHATWG')}}

Browser compatibility

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

See also