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.

Basic example

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:

// Set line width
ctx.lineWidth = 10;

// Wall
ctx.strokeRect(75, 140, 150, 110);

// Door
ctx.fillRect(130, 190, 40, 60);

// Roof
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);

The resulting drawing looks like this:


Drawing rectangles

There are three methods that immediately draw rectangles to the canvas.


Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content.


Draws a filled rectangle at (x, y) position whose size is determined by width and height.


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.

Drawing text

The following methods draw text. See also the TextMetrics object for text properties.


Draws (fills) a given text at the given (x, y) position.


Draws (strokes) a given text at the given (x, y) position.


Returns a TextMetrics object.

Line styles

The following methods and properties control how lines are drawn.


Width of lines. Default 1.0.


Type of endings on the end of lines. Possible values: butt (default), round, square.


Defines the type of corners where two lines meet. Possible values: round, bevel, miter (default).


Miter limit ratio. Default 10.


Returns the current line dash pattern array containing an even number of non-negative numbers.


Sets the current line dash pattern.


Specifies where to start a dash array on a line.

Text styles

The following properties control how text is laid out.


Font setting. Default value 10px sans-serif.


Text alignment setting. Possible values: start (default), end, left, right, center.


Baseline alignment setting. Possible values: top, hanging, middle, alphabetic (default), ideographic, bottom.


Directionality. Possible values: ltr, rtl, inherit (default).

Fill and stroke styles

Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.


Color or style to use inside shapes. Default #000 (black).


Color or style to use for the lines around shapes. Default #000 (black).

Gradients and patterns


Creates a conic gradient around a point given by coordinates represented by the parameters.


Creates a linear gradient along the line given by the coordinates represented by the parameters.


Creates a radial gradient given by the coordinates of the two circles represented by the parameters.


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.



Specifies the blurring effect. Default: 0


Color of the shadow. Default: fully-transparent black.


Horizontal distance the shadow will be offset. Default: 0.


Vertical distance the shadow will be offset. Default: 0.


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


Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.


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.


Moves the starting point of a new sub-path to the (x, y) coordinates.


Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line.


Adds a cubic Bézier curve to the current path.


Adds a quadratic Bézier curve to the current path.


Adds a circular arc to the current path.


Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line.


Adds an elliptical arc to the current path.


Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.

Drawing paths


Fills the current sub-paths with the current fill style.


Strokes the current sub-paths with the current stroke style.


If a given element is focused, this method draws a focus ring around the current path.


Scrolls the current path or a given path into the view.


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.


Reports whether or not the specified point is contained in the current path.


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 DOMMatrix objects are used in most parts of the API nowadays and will be used in the future instead.


Retrieves the current transformation matrix being applied to the context.


Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.


Adds a scaling transformation to the canvas units by x horizontally and by y vertically.


Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid.


Multiplies the current transformation matrix with the matrix described by its arguments.


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.



Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).


With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.

Drawing images


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

Pixel manipulation

See also the ImageData object.


Creates a new, blank ImageData object with the specified dimensions. All of the pixels in the new object are transparent black.


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.


Paints data from the given ImageData object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

Image smoothing

CanvasRenderingContext2D.imageSmoothingEnabled Experimental

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

CanvasRenderingContext2D.imageSmoothingQuality Experimental

Allows you to set the quality of image smoothing.

The canvas state

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:

Saves the current drawing style state using a stack so you can revert any change you make to it using restore().


Restores the drawing style state to the last element on the 'state stack' saved by save().


A read-only back-reference to the HTMLCanvasElement. Might be null if it is not associated with a <canvas> element.


Returns an object containing the actual context attributes. Context attributes can be requested with HTMLCanvasElement.getContext().


CanvasRenderingContext2D.filter Experimental

Applies a CSS or SVG filter to the canvas, e.g., to change its brightness or blurriness.

Non-standard APIs

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.

Non-Standard CanvasRenderingContext2D.isContextLost()

Inspired by the same WebGLRenderingContext method it returns true if the Canvas context has been lost, or false if not.

WebKit only

Non-Standard Deprecated CanvasRenderingContext2D.webkitBackingStorePixelRatio

The backing store size in relation to the canvas element. See High DPI Canvas.

Non-Standard Deprecated CanvasRenderingContext2D.webkitGetImageDataHD

Intended for HD backing stores, but removed from canvas specifications.

Non-Standard Deprecated CanvasRenderingContext2D.webkitPutImageDataHD

Intended for HD backing stores, but removed from canvas specifications.

Gecko only

Prefixed APIs

Non-Standard CanvasRenderingContext2D.mozImageSmoothingEnabled

See CanvasRenderingContext2D.imageSmoothingEnabled.

Non-Standard Deprecated CanvasRenderingContext2D.mozTextStyle

Introduced in Gecko 1.9, deprecated in favor of the CanvasRenderingContext2D.font property.

Non-Standard Deprecated 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.

Non-Standard Deprecated CanvasRenderingContext2D.mozMeasureText()

This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use CanvasRenderingContext2D.measureText() instead.

Non-Standard Deprecated CanvasRenderingContext2D.mozPathText()

This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.

Non-Standard Deprecated CanvasRenderingContext2D.mozTextAlongPath()

This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.

Internal APIs (chrome-context only)

Non-Standard 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.

Non-Standard 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

Non-Standard CanvasRenderingContext2D.msFillRule

The fill rule to use. This must be one of evenodd or nonzero (default).


HTML Standard
# 2dcontext

Browser compatibility

BCD tables only load in the browser

See also