The CanvasRenderingContext2D
interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a <canvas>
element. It is used for drawing shapes, text, images, and other objects.
See the interface's properties and methods in the sidebar and below. The Canvas tutorial has more explanation, examples, and resources, as well.
To get a CanvasRenderingContext2D
instance, you must first have an HTML <canvas>
element to work with:
<canvas id="my-house" width="300" height="300"></canvas>
To get the canvas' 2D rendering context, call getContext()
on the <canvas>
element, supplying '2d'
as the argument:
const canvas = document.getElementById('my-house');
const ctx = canvas.getContext('2d');
With the context in hand, you can draw anything you like. This code draws a house:
ctx.lineWidth = 10;
ctx.strokeRect(75, 140, 150, 110);
ctx.fillRect(130, 190, 40, 60);
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();
The resulting drawing looks like this:
There are three methods that immediately draw rectangles to the 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()
-
Draws a filled rectangle at (x, y) position whose size is determined by width and height.
-
CanvasRenderingContext2D.strokeRect()
-
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 draw text. See also the TextMetrics
object for text properties.
-
CanvasRenderingContext2D.fillText()
-
Draws (fills) a given text at the given (x, y) position.
-
CanvasRenderingContext2D.strokeText()
-
Draws (strokes) a given text at the given (x, y) position.
-
CanvasRenderingContext2D.measureText()
-
Returns a TextMetrics
object.
The following methods and properties control how lines are drawn.
-
CanvasRenderingContext2D.lineWidth
-
Width of lines. Default 1.0
.
-
CanvasRenderingContext2D.lineCap
-
Type of endings on the end of lines. Possible values: butt
(default), round
, square
.
-
CanvasRenderingContext2D.lineJoin
-
Defines the type of corners where two lines meet. Possible values: round
, bevel
, miter
(default).
-
CanvasRenderingContext2D.miterLimit
-
Miter limit ratio. Default 10
.
-
CanvasRenderingContext2D.getLineDash()
-
Returns the current line dash pattern array containing an even number of non-negative numbers.
-
CanvasRenderingContext2D.setLineDash()
-
Sets the current line dash pattern.
-
CanvasRenderingContext2D.lineDashOffset
-
Specifies where to start a dash array on a line.
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
, 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).
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 current sub-path to the specified (x, y) coordinates with a straight line.
-
CanvasRenderingContext2D.bezierCurveTo()
-
Adds a cubic Bézier curve to the current path.
-
CanvasRenderingContext2D.quadraticCurveTo()
-
Adds a quadratic Bézier curve to the current path.
-
CanvasRenderingContext2D.arc()
-
Adds a circular arc to the current path.
-
CanvasRenderingContext2D.arcTo()
-
Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line.
-
CanvasRenderingContext2D.ellipse()
-
Adds an elliptical arc to the current path.
-
CanvasRenderingContext2D.rect()
-
Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.
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 DOMMatrix
objects are used in most parts of the API nowadays and will be used in the future instead.
-
CanvasRenderingContext2D.getTransform()
-
Retrieves the current transformation matrix being applied to the context.
-
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 horizontally 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()
Experimental
-
Resets the current transform by the identity matrix.
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.
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.getContextAttributes()
-
Returns an object containing the actual context attributes. Context attributes can be requested with HTMLCanvasElement.getContext()
.
Most of these APIs are deprecated and were removed shortly after Chrome 36.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.clearShadow()
-
Removes all shadow settings like CanvasRenderingContext2D.shadowColor
and CanvasRenderingContext2D.shadowBlur
.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.drawImageFromRect()
-
This is redundant with an equivalent overload of drawImage
.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setAlpha()
-
Use CanvasRenderingContext2D.globalAlpha
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setCompositeOperation()
-
Use CanvasRenderingContext2D.globalCompositeOperation
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setLineWidth()
-
Use CanvasRenderingContext2D.lineWidth
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setLineJoin()
-
Use CanvasRenderingContext2D.lineJoin
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setLineCap()
-
Use CanvasRenderingContext2D.lineCap
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setMiterLimit()
-
Use CanvasRenderingContext2D.miterLimit
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setStrokeColor()
-
Use CanvasRenderingContext2D.strokeStyle
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setFillColor()
-
Use CanvasRenderingContext2D.fillStyle
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.setShadow()
-
Use CanvasRenderingContext2D.shadowColor
and CanvasRenderingContext2D.shadowBlur
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.webkitLineDash
-
Use CanvasRenderingContext2D.getLineDash()
and CanvasRenderingContext2D.setLineDash()
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.webkitLineDashOffset
-
Use CanvasRenderingContext2D.lineDashOffset
instead.
-
Non-Standard
Deprecated
CanvasRenderingContext2D.webkitImageSmoothingEnabled
-
Use CanvasRenderingContext2D.imageSmoothingEnabled
instead.