--- title: Canvas API slug: Web/API/Canvas_API translation_of: Web/API/Canvas_API ---
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.
This simple example draws a green rectangle onto a canvas.
<canvas id="canvas"></canvas>
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);
{{ EmbedLiveSample('Basic_example', 700, 180) }}
Note: The interfaces related to the WebGLRenderingContext
are referenced under WebGL.
{{domxref("CanvasCaptureMediaStream")}} is a related interface.
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.
Specification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}} | {{Spec2('HTML WHATWG')}} |
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>
.