Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

CanvasRenderingContext2D

この翻訳は不完全です。英語から この記事を翻訳 してください。

CanvasRenderingContext2D インターフェイスは、<canvas> 要素に描画するための2Dレンダリングコンテキストを提供します。

このインターフェイスのオブジェクトを取得するには、以下のように<canvas>のgetContext()の引数に"2d"を指定して 呼び出します。

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');

いったん2Dレンダリングコンテキストを取得すれば、それを用いてcanvasに描画することができます。

ctx.fillStyle = "rgb(200,0,0)";  
ctx.fillRect(10, 10, 55, 50);  

詳細は、サイドバーや以下にあるプロパティとメソッドの説明を参照してください。
Canvas tutorial には同様の説明と、より多くのサンプルコードがあります。

矩形の描画

ビットマップに対して矩形を直接描画する方法は三つあります。

CanvasRenderingContext2D.clearRect()
座標(x, y)を始点とする大きさ(width, height)の領域を、透明色(透明な黒)で塗りつぶします。
領域内に描画されていたすべてのコンテンツは消去されます。
CanvasRenderingContext2D.fillRect()
現在の塗りつぶしスタイルを用いて、領域内を塗りつぶします。
CanvasRenderingContext2D.strokeRect()
現在のストロークスタイルを用いて、領域の枠線を描画します。

文字列の描画

文字列の描画を提供します。
文字列のプロパティについてはTextMetrics を参照してください。

CanvasRenderingContext2D.fillText()
現在の塗りつぶしスタイルを用いて、文字の内部を塗りつぶします。
CanvasRenderingContext2D.strokeText()
現在のストロークスタイルを用いて、文字の輪郭を描画します。
CanvasRenderingContext2D.measureText()
TextMetrics オブジェクトを返します。

線のスタイル

線がどのように描画されるかを設定・取得します。

CanvasRenderingContext2D.lineWidth
線の幅を設定します。デフォルトは1.0です。
CanvasRenderingContext2D.lineCap
線の末端のスタイルを設定します。設定可能な値はbutt (デフォルト), round, squareです。
CanvasRenderingContext2D.lineJoin
二つの直線が出会う頂点のスタイルを設定します。設定可能な値はround, bevel, miter (デフォルト)です。
CanvasRenderingContext2D.miterLimit
Miter limit を設定します。デフォルトは10です。
CanvasRenderingContext2D.getLineDash()
現在の破線パターンを格納した配列を取得します。
この配列には負でない実数が偶数個含まれています。
CanvasRenderingContext2D.setLineDash()
破線パターンを指定します。
CanvasRenderingContext2D.lineDashOffset
線のどこから破線にするかを指定します。

文字列のスタイル

The following properties control how text is laid out.

CanvasRenderingContext2D.font
Font setting. Default value 10px sans-serif.
CanvasRenderingContext2D.textAlign
Text alignment setting. Possible values: start (default), end, left, right or center.
CanvasRenderingContext2D.textBaseline
Baseline alignment setting. Possible values: top, hanging, middle, alphabetic (default), ideographic, bottom.
CanvasRenderingContext2D.direction
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
Color or style to use inside shapes. Default #000 (black).
CanvasRenderingContext2D.strokeStyle
Color or style to use for the lines around shapes. Default #000 (black).

グラデーションとパターン

CanvasRenderingContext2D.createLinearGradient()
Creates a linear gradient along the line given by the coordinates represented by the parameters.
CanvasRenderingContext2D.createRadialGradient()
Creates a radial gradient along the line given by the coordinates represented by the parameters.
CanvasRenderingContext2D.createPattern()
Creates a pattern using the specified image (a CanvasImageSource). It repeats the source in the directions specified by the repetition argument. This method returns a CanvasPattern.

影のスタイル

CanvasRenderingContext2D.shadowBlur
Specifies the blurring effect. Default 0
CanvasRenderingContext2D.shadowColor
Color of the shadow. Default fully-transparent black.
CanvasRenderingContext2D.shadowOffsetX
Horizontal distance the shadow will be offset. Default 0.
CanvasRenderingContext2D.shadowOffsetY
Vertical distance the shadow will be offset. Default 0.

パスの作成

The following methods can be used to manipulate paths of objects.

CanvasRenderingContext2D.beginPath()
Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
CanvasRenderingContext2D.closePath()
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()
Moves the starting point of a new sub-path to the (x, y) coordinates.
CanvasRenderingContext2D.lineTo()
Connects the last point in the subpath to the x, y coordinates with a straight line.
CanvasRenderingContext2D.bezierCurveTo()
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()
Adds a quadratic Bézier curve to the current path.
CanvasRenderingContext2D.arc()
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()
Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.
CanvasRenderingContext2D.ellipse()
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()
Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.

パスを描画する

CanvasRenderingContext2D.fill()
Fills the subpaths with the current fill style.
CanvasRenderingContext2D.stroke()
Strokes the subpaths with the current stroke style.
CanvasRenderingContext2D.drawFocusIfNeeded()
If a given element is focused, this method draws a focus ring around the current path.
CanvasRenderingContext2D.scrollPathIntoView()
Scrolls the current path or a given path into the view.
CanvasRenderingContext2D.clip()
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()
Reports whether or not the specified point is contained in the current path.
CanvasRenderingContext2D.isPointInStroke()
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 objects. The methods listed below remain for historical and compatibility reasons as SVGMatrix objects are used in most parts of the API nowadays and will be used in the future instead.

CanvasRenderingContext2D.currentTransform
Current transformation matrix (SVGMatrix object).
CanvasRenderingContext2D.rotate()
Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
CanvasRenderingContext2D.scale()
Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
CanvasRenderingContext2D.translate()
Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
CanvasRenderingContext2D.transform()
Multiplies the current transformation matrix with the matrix described by its arguments.
CanvasRenderingContext2D.setTransform()
Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments.
CanvasRenderingContext2D.resetTransform()
Resets the current transform by the identity matrix.

透明度と合成

CanvasRenderingContext2D.globalAlpha
Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
CanvasRenderingContext2D.globalCompositeOperation
With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.

画像の描画

CanvasRenderingContext2D.drawImage()
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.

ピクセル操作

See also the ImageData object.

CanvasRenderingContext2D.createImageData()
Creates a new, blank ImageData object with the specified dimensions. All of the pixels in the new object are transparent black.
CanvasRenderingContext2D.getImageData()
Returns an ImageData 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()
Paints data from the given ImageData object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

画像の平滑化

CanvasRenderingContext2D.imageSmoothingEnabled
Image smoothing mode; if disabled, images will not be smoothed if scaled.

キャンバスの状態

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()
Saves the current drawing style state using a stack so you can revert any change you make to it using restore().
CanvasRenderingContext2D.restore()
Restores the drawing style state to the last element on the 'state stack' saved by save().
CanvasRenderingContext2D.canvas
A read-only back-reference to the HTMLCanvasElement. Might be null 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

Most of these APIs are deprecated and will be removed in the future.

CanvasRenderingContext2D.clearShadow()
Removes all shadow settings like CanvasRenderingContext2D.shadowColor and CanvasRenderingContext2D.shadowBlur.
CanvasRenderingContext2D.drawImageFromRect()
This is redundant with an equivalent overload of drawImage.
CanvasRenderingContext2D.setAlpha()
Use CanvasRenderingContext2D.globalAlpha instead.
CanvasRenderingContext2D.setCompositeOperation()
Use CanvasRenderingContext2D.globalCompositeOperation instead.
CanvasRenderingContext2D.setLineWidth()
Use CanvasRenderingContext2D.lineWidth instead.
CanvasRenderingContext2D.setLineJoin()
Use CanvasRenderingContext2D.lineJoin instead.
CanvasRenderingContext2D.setLineCap()
Use CanvasRenderingContext2D.lineCap instead.
CanvasRenderingContext2D.setMiterLimit()
Use CanvasRenderingContext2D.miterLimit instead.
CanvasRenderingContext2D.setStrokeColor()
Use CanvasRenderingContext2D.strokeStyle instead.
CanvasRenderingContext2D.setFillColor()
Use CanvasRenderingContext2D.fillStyle instead.
CanvasRenderingContext2D.setShadow()
Use CanvasRenderingContext2D.shadowColor and CanvasRenderingContext2D.shadowBlur instead.
CanvasRenderingContext2D.webkitLineDash
Use CanvasRenderingContext2D.getLineDash() and CanvasRenderingContext2D.setLineDash() instead.
CanvasRenderingContext2D.webkitLineDashOffset
Use CanvasRenderingContext2D.lineDashOffset instead.
CanvasRenderingContext2D.webkitImageSmoothingEnabled
Use CanvasRenderingContext2D.imageSmoothingEnabled instead.
CanvasRenderingContext2D.getContextAttributes()
Inspired by the same WebGLRenderingContext method it returns an Canvas2DContextAttributes 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 returns true if the Canvas context has been lost, or false if not.

WebKit only

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 only

CanvasRenderingContext2D.filter
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
CanvasRenderingContext2D.mozCurrentTransformInverse
Sets or gets the current inversed transformation matrix. 
CanvasRenderingContext2D.mozFillRule
The fill rule to use. This must be one of evenodd or nonzero (default).
CanvasRenderingContext2D.mozImageSmoothingEnabled
See CanvasRenderingContext2D.imageSmoothingEnabled.
CanvasRenderingContext2D.mozDash
An array which specifies the lengths of alternating dashes and gaps . Use CanvasRenderingContext2D.getLineDash() and CanvasRenderingContext2D.setLineDash() instead.
CanvasRenderingContext2D.mozDashOffset
Specifies where to start a dash array on a line. . Use CanvasRenderingContext2D.lineDashOffset instead.
CanvasRenderingContext2D.mozTextStyle
Introduced in in Gecko 1.9, deprecated in favor of the CanvasRenderingContext2D.font property.
CanvasRenderingContext2D.mozDrawText()
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use CanvasRenderingContext2D.strokeText() or CanvasRenderingContext2D.fillText() instead.
CanvasRenderingContext2D.mozMeasureText()
This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use CanvasRenderingContext2D.measureText() 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()
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 or nonzero (default).

仕様

Specification Status Comment
WHATWG HTML Living Standard
CanvasRenderingContext2D の定義
現行の標準  

ブラウザ間の互換性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1 1.5 (1.8) 9 9 2
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ? ?

互換性に関する注釈

  • Starting with Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), 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, shadowOffsetYshadowBlur.

関連項目

ドキュメントのタグと貢献者

 このページの貢献者: hikalium
 最終更新者: hikalium,