CanvasRenderingContext2D
<canvas>
元素外觀的 2D 渲染環境。
要取得此實作此介面的實體物件,可以於一個 <canvas>
元素上以 "2d" 為參數呼叫 getContext()
(en-US) 方法:
var canvas = document.getElementById("mycanvas"); // in your HTML this element appears as <canvas id="mycanvas"></canvas>
var ctx = canvas.getContext("2d");
只要你有了 canvas 的 2D 繪製背景物件,你就可以在其中繪圖。 舉個例子:
ctx.fillStyle = "rgb(200,0,0)"; // sets the color to fill in the rectangle with
ctx.fillRect(10, 10, 55, 50); // draws the rectangle at position 10, 10 with a width of 55 and a height of 50
canvas 教學有更多資訊、範例,以及資源。
繪製矩形
有三個函式可以馬上在點陣圖上畫出長方形。
CanvasRenderingContext2D.clearRect()
-
Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content.
CanvasRenderingContext2D.fillRect()
(en-US)-
Draws a filled rectangle at (x, y) position whose size is determined by width and height.
CanvasRenderingContext2D.strokeRect()
(en-US)-
Paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style.
繪製文字
The following methods are provided for drawing text. See also the TextMetrics
(en-US) object for text properties.
CanvasRenderingContext2D.fillText()
(en-US)-
Draws (fills) a given text at the given (x,y) position.
CanvasRenderingContext2D.strokeText()
(en-US)-
Draws (strokes) a given text at the given (x, y) position.
CanvasRenderingContext2D.measureText()
(en-US)-
Returns a
TextMetrics
(en-US) object.
線條樣式
The following methods and properties control how lines are drawn.
CanvasRenderingContext2D.lineWidth
(en-US)-
Width of lines. Default
1.0
CanvasRenderingContext2D.lineCap
(en-US)-
Type of endings on the end of lines. Possible values:
butt
(default),round
,square
. CanvasRenderingContext2D.lineJoin
(en-US)-
Defines the type of corners where two lines meet. Possible values:
round
,bevel
,miter
(default). CanvasRenderingContext2D.miterLimit
(en-US)-
Miter limit ratio. Default
10
. CanvasRenderingContext2D.getLineDash()
(en-US)-
Returns the current line dash pattern array containing an even number of non-negative numbers.
CanvasRenderingContext2D.setLineDash()
(en-US)-
Sets the current line dash pattern.
CanvasRenderingContext2D.lineDashOffset
(en-US)-
Specifies where to start a dash array on a line.
文字樣式
The following properties control how text is laid out.
CanvasRenderingContext2D.font
(en-US)-
Font setting. Default value
10px sans-serif
. CanvasRenderingContext2D.textAlign
(en-US)-
Text alignment setting. Possible values:
start
(default),end
,left
,right
orcenter
. CanvasRenderingContext2D.textBaseline
(en-US)-
Baseline alignment setting. Possible values:
top
,hanging
,middle
,alphabetic
(default),ideographic
,bottom
. CanvasRenderingContext2D.direction
(en-US)-
Directionality. Possible values:
ltr, rtl
,inherit
(default).
填充及邊線樣式
Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.
CanvasRenderingContext2D.fillStyle
(en-US)-
Color or style to use inside shapes. Default
#000
(black). CanvasRenderingContext2D.strokeStyle
(en-US)-
Color or style to use for the lines around shapes. Default
#000
(black).
漸層填色及圖案填充
CanvasRenderingContext2D.createLinearGradient()
(en-US)-
Creates a linear gradient along the line given by the coordinates represented by the parameters.
CanvasRenderingContext2D.createRadialGradient()
(en-US)-
Creates a radial gradient given by the coordinates of the two circles represented by the parameters.
CanvasRenderingContext2D.createPattern()
(en-US)-
Creates a pattern using the specified image (a
CanvasImageSource
(en-US)). It repeats the source in the directions specified by the repetition argument. This method returns aCanvasPattern
(en-US).
陰影
CanvasRenderingContext2D.shadowBlur
(en-US)-
Specifies the blurring effect. Default
0
CanvasRenderingContext2D.shadowColor
(en-US)-
Color of the shadow. Default fully-transparent black.
CanvasRenderingContext2D.shadowOffsetX
(en-US)-
Horizontal distance the shadow will be offset. Default 0.
CanvasRenderingContext2D.shadowOffsetY
(en-US)-
Vertical distance the shadow will be offset. Default 0.
路徑
The following methods can be used to manipulate paths of objects.
CanvasRenderingContext2D.beginPath()
(en-US)-
Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
CanvasRenderingContext2D.closePath()
(en-US)-
Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.
CanvasRenderingContext2D.moveTo()
(en-US)-
Moves the starting point of a new sub-path to the (x, y) coordinates.
CanvasRenderingContext2D.lineTo()
(en-US)-
Connects the last point in the subpath to the
x, y
coordinates with a straight line. CanvasRenderingContext2D.bezierCurveTo()
(en-US)-
Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using
moveTo()
before creating the Bézier curve. CanvasRenderingContext2D.quadraticCurveTo()
(en-US)-
Adds a quadratic Bézier curve to the current path.
CanvasRenderingContext2D.arc()
(en-US)-
Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
CanvasRenderingContext2D.arcTo()
(en-US)-
Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.
CanvasRenderingContext2D.ellipse()
(en-US) 實驗性質-
Adds an ellipse to the path which is centered at (x, y) position with the radii radiusX and radiusY starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
CanvasRenderingContext2D.rect()
(en-US)-
Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.
繪製路徑
CanvasRenderingContext2D.fill()
(en-US)-
Fills the subpaths with the current fill style.
CanvasRenderingContext2D.stroke()
(en-US)-
Strokes the subpaths with the current stroke style.
CanvasRenderingContext2D.drawFocusIfNeeded()
(en-US)-
If a given element is focused, this method draws a focus ring around the current path.
CanvasRenderingContext2D.scrollPathIntoView()
(en-US)-
Scrolls the current path or a given path into the view.
CanvasRenderingContext2D.clip()
(en-US)-
Creates a clipping path from the current sub-paths. Everything drawn after
clip()
is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial. CanvasRenderingContext2D.isPointInPath()
(en-US)-
Reports whether or not the specified point is contained in the current path.
CanvasRenderingContext2D.isPointInStroke()
(en-US)-
Reports whether or not the specified point is inside the area contained by the stroking of a path.
變形
Objects in the CanvasRenderingContext2D
rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and Path2D
(en-US) objects. The methods listed below remain for historical and compatibility reasons as SVGMatrix
(en-US) objects are used in most parts of the API nowadays and will be used in the future instead.
CanvasRenderingContext2D.currentTransform
(en-US)-
Current transformation matrix (
SVGMatrix
(en-US) object). CanvasRenderingContext2D.rotate()
(en-US)-
Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
CanvasRenderingContext2D.scale()
(en-US)-
Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
CanvasRenderingContext2D.translate()
(en-US)-
Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
CanvasRenderingContext2D.transform()
(en-US)-
Multiplies the current transformation matrix with the matrix described by its arguments.
CanvasRenderingContext2D.setTransform()
(en-US)-
Resets the current transform to the identity matrix, and then invokes the
transform()
method with the same arguments. CanvasRenderingContext2D.resetTransform()
(en-US) 實驗性質-
Resets the current transform by the identity matrix.
合成
CanvasRenderingContext2D.globalAlpha
(en-US)-
Alpha value that is applied to shapes and images before they are composited onto the canvas. Default
1.0
(opaque). CanvasRenderingContext2D.globalCompositeOperation
(en-US)-
With
globalAlpha
applied this sets how shapes and images are drawn onto the existing bitmap.
繪製圖形
CanvasRenderingContext2D.drawImage()
(en-US)-
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
像素控制
See also the ImageData
(en-US) object.
CanvasRenderingContext2D.createImageData()
(en-US)-
Creates a new, blank
ImageData
(en-US) object with the specified dimensions. All of the pixels in the new object are transparent black. CanvasRenderingContext2D.getImageData()
(en-US)-
Returns an
ImageData
(en-US) object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height. CanvasRenderingContext2D.putImageData()
(en-US)-
Paints data from the given
ImageData
(en-US) object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
圖像平滑
CanvasRenderingContext2D.imageSmoothingEnabled
(en-US) 實驗性質-
Image smoothing mode; if disabled, images will not be smoothed if scaled.
canvas 狀態
The CanvasRenderingContext2D
rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:
CanvasRenderingContext2D.save()
(en-US)-
Saves the current drawing style state using a stack so you can revert any change you make to it using
restore()
. CanvasRenderingContext2D.restore()
(en-US)-
Restores the drawing style state to the last element on the 'state stack' saved by
save()
. CanvasRenderingContext2D.canvas
(en-US)-
A read-only back-reference to the
HTMLCanvasElement
. Might benull
if it is not associated with a<canvas>
element.
點擊區域
CanvasRenderingContext2D.addHitRegion()
實驗性質-
Adds a hit region to the canvas.
CanvasRenderingContext2D.removeHitRegion()
實驗性質-
Removes the hit region with the specified
id
from the canvas. CanvasRenderingContext2D.clearHitRegions()
實驗性質-
Removes all hit regions from the canvas.
非標準 API
Blink 及 WebKit 引擎
Most of these APIs are deprecated and will be removed in the future.
-
非標準
CanvasRenderingContext2D.clearShadow()
-
Removes all shadow settings like
CanvasRenderingContext2D.shadowColor
(en-US) andCanvasRenderingContext2D.shadowBlur
(en-US). -
非標準
CanvasRenderingContext2D.drawImageFromRect()
-
This is redundant with an equivalent overload of
drawImage
. -
非標準
CanvasRenderingContext2D.setAlpha()
-
Use
CanvasRenderingContext2D.globalAlpha
(en-US) instead. -
非標準
CanvasRenderingContext2D.setCompositeOperation()
-
Use
CanvasRenderingContext2D.globalCompositeOperation
(en-US) instead. -
非標準
CanvasRenderingContext2D.setLineWidth()
-
Use
CanvasRenderingContext2D.lineWidth
(en-US) instead. -
非標準
CanvasRenderingContext2D.setLineJoin()
-
Use
CanvasRenderingContext2D.lineJoin
(en-US) instead. -
非標準
CanvasRenderingContext2D.setLineCap()
-
Use
CanvasRenderingContext2D.lineCap
(en-US) instead. -
非標準
CanvasRenderingContext2D.setMiterLimit()
-
Use
CanvasRenderingContext2D.miterLimit
(en-US) instead. -
非標準
CanvasRenderingContext2D.setStrokeColor()
-
Use
CanvasRenderingContext2D.strokeStyle
(en-US) instead. -
非標準
CanvasRenderingContext2D.setFillColor()
-
Use
CanvasRenderingContext2D.fillStyle
(en-US) instead. -
非標準
CanvasRenderingContext2D.setShadow()
-
Use
CanvasRenderingContext2D.shadowColor
(en-US) andCanvasRenderingContext2D.shadowBlur
(en-US) instead. -
非標準
CanvasRenderingContext2D.webkitLineDash
-
Use
CanvasRenderingContext2D.getLineDash()
(en-US) andCanvasRenderingContext2D.setLineDash()
(en-US) instead. -
非標準
CanvasRenderingContext2D.webkitLineDashOffset
-
Use
CanvasRenderingContext2D.lineDashOffset
(en-US) instead. -
非標準
CanvasRenderingContext2D.webkitImageSmoothingEnabled
-
Use
CanvasRenderingContext2D.imageSmoothingEnabled
(en-US) instead.
Blink 引擎專屬
-
非標準
CanvasRenderingContext2D.getContextAttributes()
-
Inspired by the same
WebGLRenderingContext
method it returns anCanvas2DContextAttributes
object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (true
by default) to indicate that transparency is used in the canvas. -
非標準
CanvasRenderingContext2D.isContextLost()
-
Inspired by the same
WebGLRenderingContext
method it returnstrue
if the Canvas context has been lost, orfalse
if not.
WebKit 引擎專屬
-
非標準
CanvasRenderingContext2D.webkitBackingStorePixelRatio
-
The backing store size in relation to the canvas element. See High DPI Canvas.
-
非標準
CanvasRenderingContext2D.webkitGetImageDataHD
-
Intended for HD backing stores, but removed from canvas specifications.
-
非標準
CanvasRenderingContext2D.webkitPutImageDataHD
-
Intended for HD backing stores, but removed from canvas specifications.
Gecko 引擎專屬
-
非標準
CanvasRenderingContext2D.filter
(en-US) -
CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.
Prefixed APIs
-
非標準
CanvasRenderingContext2D.mozCurrentTransform
-
Sets or gets the current transformation matrix, see
CanvasRenderingContext2D.currentTransform
(en-US). -
非標準
CanvasRenderingContext2D.mozCurrentTransformInverse
-
Sets or gets the current inversed transformation matrix.
-
非標準
CanvasRenderingContext2D.mozImageSmoothingEnabled
-
非標準
已棄用
CanvasRenderingContext2D.mozDash
-
An array which specifies the lengths of alternating dashes and gaps. Use
CanvasRenderingContext2D.getLineDash()
(en-US) andCanvasRenderingContext2D.setLineDash()
(en-US) instead. -
非標準
已棄用
CanvasRenderingContext2D.mozDashOffset
-
Specifies where to start a dash array on a line. Use
CanvasRenderingContext2D.lineDashOffset
(en-US) instead. -
非標準
已棄用
CanvasRenderingContext2D.mozTextStyle
-
Introduced in in Gecko 1.9, deprecated in favor of the
CanvasRenderingContext2D.font
(en-US) property. -
非標準
已棄用
CanvasRenderingContext2D.mozDrawText()
-
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use
CanvasRenderingContext2D.strokeText()
(en-US) orCanvasRenderingContext2D.fillText()
(en-US) instead. -
非標準
已棄用
CanvasRenderingContext2D.mozMeasureText()
-
This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use
CanvasRenderingContext2D.measureText()
(en-US) instead. -
非標準
已棄用
CanvasRenderingContext2D.mozPathText()
-
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
-
非標準
已棄用
CanvasRenderingContext2D.mozTextAlongPath()
-
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
Internal APIs (chrome-context only)
-
非標準
CanvasRenderingContext2D.asyncDrawXULElement()
-
Renders a region of a XUL element into the
canvas
. -
非標準
CanvasRenderingContext2D.drawWindow()
(en-US) -
Renders a region of a window into the
canvas
. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling. -
非標準
CanvasRenderingContext2D.demote()
-
This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.
Internet Explorer
-
非標準
CanvasRenderingContext2D.msFillRule
-
The fill rule to use. This must be one of
evenodd
ornonzero
(default).
規範
Specification |
---|
HTML Standard # 2dcontext |
瀏覽器相容性
BCD tables only load in the browser
相容性註記
- Starting with Gecko 5.0, specifying invalid values are now silently ignored for the following methods and properties:
translate()
,transform()
,rotate()
,scale()
,rect()
,clearRect()
,fillRect()
,strokeRect()
,lineTo()
,moveTo()
,quadraticCurveTo()
,arc()
,shadowOffsetX
,shadowOffsetY
,shadowBlur
.