画布 API
provides a means for drawing graphics via
JavaScript
和
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.
This simple example draws a green rectangle onto a canvas.
<canvas id="canvas"></canvas>
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
接口。
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);
HTMLCanvasElement
CanvasRenderingContext2D
CanvasGradient
CanvasImageSource
CanvasPattern
ImageBitmap
ImageData
RenderingContext
TextMetrics
OffscreenCanvas
Path2D
ImageBitmapRenderingContext
注意:
The interfaces related to the
WebGLRenderingContext
are referenced under
WebGL
.
CanvasCaptureMediaStream
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.
A demo of ray-tracing animation using canvas.
<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.
注意: 见 WebGL API for 2D and 3D libaries that use WebGL.
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'the 2D rendering context' in that specification. |
实时标准 |
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>
.