1. 4.12.5 The canvas element
        1. 4.12.5.1 The 2D rendering context
          1. 4.12.5.1.1 Implementation notes
          2. 4.12.5.1.2 The canvas state
          3. 4.12.5.1.3 Line styles
          4. 4.12.5.1.4 Text styles
          5. 4.12.5.1.5 Building paths
          6. 4.12.5.1.6 Path2D objects
          7. 4.12.5.1.7 Transformations
          8. 4.12.5.1.8 Image sources for 2D rendering contexts
          9. 4.12.5.1.9 Fill and stroke styles
          10. 4.12.5.1.10 Drawing rectangles to the bitmap
          11. 4.12.5.1.11 Drawing text to the bitmap
          12. 4.12.5.1.12 Drawing paths to the canvas
          13. 4.12.5.1.13 Drawing focus rings and scrolling paths into view
          14. 4.12.5.1.14 Drawing images
          15. 4.12.5.1.15 Pixel manipulation
          16. 4.12.5.1.16 Compositing
          17. 4.12.5.1.17 Image smoothing
          18. 4.12.5.1.18 Shadows
          19. 4.12.5.1.19 Filters
          20. 4.12.5.1.20 Working with externally-defined SVG filters
          21. 4.12.5.1.21 Best practices
          22. 4.12.5.1.22 Examples
        2. 4.12.5.2 The ImageBitmap rendering context
          1. 4.12.5.2.1 Introduction
          2. 4.12.5.2.2 The ImageBitmapRenderingContext interface
        3. 4.12.5.3 The OffscreenCanvas interface
          1. 4.12.5.3.1 The offscreen 2D rendering context
        4. 4.12.5.4 Serializing bitmaps to a file

4.12.5 The canvas element

Element/canvas

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+
caniuse.com table
Categories:
Flow content.
Phrasing content.
Embedded content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Transparent, but with no interactive content descendants except for a elements, img elements with usemap attributes, button elements, input elements whose type attribute are in the Checkbox or Radio Button states, input elements that are buttons, and select elements with a multiple attribute or a display size greater than 1.
Tag omission in text/html:
Neither tag is omissible.
Content attributes:
Global attributes
width — Horizontal dimension
height — Vertical dimension
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLCanvasElement.

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.

Authors should not use the canvas element in a document when a more suitable element is available. For example, it is inappropriate to use a canvas element to render a page heading: if the desired presentation of the heading is graphically intense, it should be marked up using appropriate elements (typically h1) and then styled using CSS and supporting technologies such as shadow trees.

When authors use the canvas element, they must also provide content that, when presented to the user, conveys essentially the same function or purpose as the canvas's bitmap. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element's fallback content.


In interactive visual media, if scripting is enabled for the canvas element, and if support for canvas elements has been enabled, then the canvas element represents embedded content consisting of a dynamically created image, the element's bitmap.

In non-interactive, static, visual media, if the canvas element has been previously associated with a rendering context (e.g. if the page was viewed in an interactive visual medium and is now being printed, or if some script that ran during the page layout process painted on the element), then the canvas element represents embedded content with the element's current bitmap and size. Otherwise, the element represents its fallback content instead.

In non-visual media, and in visual media if scripting is disabled for the canvas element or if support for canvas elements has been disabled, the canvas element represents its fallback content instead.

When a canvas element represents embedded content, the user can still focus descendants of the canvas element (in the fallback content). When an element is focused, it is the target of keyboard interaction events (even though the element itself is not visible). This allows authors to make an interactive canvas keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable areas in the fallback content. (Focus has no effect on mouse interaction events.) [UIEVENTS]

An element whose nearest canvas element ancestor is being rendered and represents embedded content is an element that is being used as relevant canvas fallback content.


HTMLCanvasElement/width

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

HTMLCanvasElement/height

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The canvas element has two attributes to control the size of the element's bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The width attribute defaults to 300, and the height attribute defaults to 150.

When setting the value of the width or height attribute, if the context mode of the canvas element is set to placeholder, the user agent must throw an "InvalidStateError" DOMException and leave the attribute's value unchanged.

The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the element's bitmap.

The user agent must use a square pixel density consisting of one pixel of image data per coordinate space unit for the bitmaps of a canvas and its rendering contexts.

A canvas element can be sized arbitrarily by a style sheet, its bitmap is then subject to the 'object-fit' CSS property.


context = canvas . getContext(contextId [, options ] )

HTMLCanvasElement/getContext

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns an object that exposes an API for drawing on the canvas. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API.

This specification defines the "2d" and "bitmaprenderer" contexts below. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL]

Returns null if contextId is not supported, or if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context).

url = canvas . toDataURL( [ type [, quality ] ] )

HTMLCanvasElement/toDataURL

Support in all current engines.

Firefox2+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns a data: URL for the image in the canvas.

The first argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is "image/png"; that type is also used if the given type isn't supported. The second argument applies if the type is an image format that supports variable quality (such as "image/jpeg"), and is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image.

When trying to use types other than "image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".)

canvas . toBlob(callback [, type [, quality ] ] )

HTMLCanvasElement/toBlob

Support in all current engines.

Firefox19+Safari11+Chrome50+
Opera37+Edge79+
Edge (Legacy)NoInternet Explorer🔰 10+
Firefox Android4+Safari iOS11+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+

Creates a Blob object representing a file containing the image in the canvas, and invokes a callback with a handle to that object.

The second argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is "image/png"; that type is also used if the given type isn't supported. The third argument applies if the type is an image format that supports variable quality (such as "image/jpeg"), and is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image.

canvas . transferControlToOffscreen()

HTMLCanvasElement/transferControlToOffscreen

Firefox🔰 44+SafariNoChrome69+
OperaNoEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 44+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera AndroidNo

Returns a newly created OffscreenCanvas object that uses the canvas element as a placeholder. Once the canvas element has become a placeholder for an OffscreenCanvas object, its intrinsic size can no longer be changed, and it cannot have a rendering context. The content of the placeholder canvas is updated by calling the commit() method of the OffscreenCanvas object's rendering context.

4.12.5.1 The 2D rendering context

CanvasRenderingContext2D

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
context = canvas . getContext('2d' [, { [ alpha: true ] [, desynchronized: false ] } ] )

Returns a CanvasRenderingContext2D object that is permanently bound to a particular canvas element.

If the alpha member is false, then the context is forced to always be opaque.

If the desynchronized member is true, then the context might be desynchronized.

context . canvas

CanvasRenderingContext2D/canvas

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the canvas element.

attributes = canvas . getContextAttributes()

Returns an object whose:


The CanvasFillRule enumeration is used to select the fill rule algorithm by which to determine if a point is inside or outside a path.

The value "nonzero" value indicates the nonzero winding rule, wherein a point is considered to be outside a shape if the number of times a half-infinite straight line drawn from that point crosses the shape's path going in one direction is equal to the number of times it crosses the path going in the other direction.

The "evenodd" value indicates the even-odd rule, wherein a point is considered to be outside a shape if the number of times a half-infinite straight line drawn from that point crosses the shape's path is even.

If a point is not outside a shape, it is inside the shape.


The ImageSmoothingQuality enumeration is used to express a preference for the interpolation quality to use when smoothing images.

The "low" value indicates a preference for a low level of image interpolation quality. Low-quality image interpolation may be more computationally efficient than higher settings.

The "medium" value indicates a preference for a medium level of image interpolation quality.

The "high" value indicates a preference for a high level of image interpolation quality. High-quality image interpolation may be more computationally expensive than lower settings.

Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-smoothing algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used.

4.12.5.1.1 Implementation notes

The output bitmap, when it is not directly displayed by the user agent, implementations can, instead of updating this bitmap, merely remember the sequence of drawing operations that have been applied to it until such time as the bitmap's actual data is needed (for example because of a call to drawImage(), or the createImageBitmap() factory method). In many cases, this will be more memory efficient.

The bitmap of a canvas element is the one bitmap that's pretty much always going to be needed in practice. The output bitmap of a rendering context, when it has one, is always just an alias to a canvas element's bitmap.

Additional bitmaps are sometimes needed, e.g. to enable fast drawing when the canvas is being painted at a different size than its intrinsic size, or to enable double buffering so that graphics updates, like page scrolling for example, can be processed concurrently while canvas draw commands are being executed.

4.12.5.1.2 The canvas state

Objects that implement the CanvasState interface maintain a stack of drawing states. Drawing states consist of:

The current default path and the rendering context's bitmaps are not part of the drawing state. The current default path is persistent, and can only be reset using the beginPath() method. The bitmaps depend on whether and how the rendering context is bound to a canvas element.

context . save()

CanvasRenderingContext2D/save

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Pushes the current state onto the stack.

context . restore()

CanvasRenderingContext2D/restore

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Pops the top state on the stack, restoring the context to that state.

4.12.5.1.3 Line styles
context . lineWidth [ = value ]

CanvasRenderingContext2D/lineWidth

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . lineWidth [ = value ]

Returns the current line width.

Can be set, to change the line width. Values that are not finite values greater than zero are ignored.

context . lineCap [ = value ]

CanvasRenderingContext2D/lineCap

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . lineCap [ = value ]

Returns the current line cap style.

Can be set, to change the line cap style.

The possible line cap styles are "butt", "round", and "square". Other values are ignored.

context . lineJoin [ = value ]

CanvasRenderingContext2D/lineJoin

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . lineJoin [ = value ]

Returns the current line join style.

Can be set, to change the line join style.

The possible line join styles are "bevel", "round", and "miter". Other values are ignored.

context . miterLimit [ = value ]

CanvasRenderingContext2D/miterLimit

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . miterLimit [ = value ]

Returns the current miter limit ratio.

Can be set, to change the miter limit ratio. Values that are not finite values greater than zero are ignored.

context . setLineDash(segments)

CanvasRenderingContext2D/setLineDash

Support in all current engines.

Firefox27+Safari6.1+Chrome23+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android37+Samsung Internet1.5+Opera Android14+
styles . setLineDash(segments)

Sets the current line dash pattern (as used when stroking). The argument is a list of distances for which to alternately have the line on and the line off.

segments = context . getLineDash()

CanvasRenderingContext2D/getLineDash

Support in all current engines.

Firefox27+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
segments = styles . getLineDash()

Returns a copy of the current line dash pattern. The array returned will always have an even number of entries (i.e. the pattern is normalized).

context . lineDashOffset

CanvasRenderingContext2D/lineDashOffset

Support in all current engines.

Firefox27+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . lineDashOffset

Returns the phase offset (in the same units as the line dash pattern).

Can be set, to change the phase offset. Values that are not finite values are ignored.

4.12.5.1.4 Text styles
context . font [ = value ]

CanvasRenderingContext2D/font

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . font [ = value ]

Returns the current font settings.

Can be set, to change the font. The syntax is the same as for the CSS 'font' property; values that cannot be parsed as CSS font values are ignored.

Relative keywords and lengths are computed relative to the font of the canvas element.

context . textAlign [ = value ]

CanvasRenderingContext2D/textAlign

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . textAlign [ = value ]

Returns the current text alignment settings.

Can be set, to change the alignment. The possible values are and their meanings are given below. Other values are ignored. The default is "start".

context . textBaseline [ = value ]

CanvasRenderingContext2D/textBaseline

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
styles . textBaseline [ = value ]

Returns the current baseline alignment settings.

Can be set, to change the baseline alignment. The possible values and their meanings are given below. Other values are ignored. The default is "alphabetic".

context . direction [ = value ]

CanvasRenderingContext2D/direction

FirefoxNoSafariYesChrome🔰 Yes
OperaNoEdge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidNo
styles . direction [ = value ]

Returns the current directionality.

Can be set, to change the directionality. The possible values and their meanings are given below. Other values are ignored. The default is "inherit".

The textAlign attribute's allowed keywords are as follows:

start

Align to the start edge of the text (left side in left-to-right text, right side in right-to-left text).

end

Align to the end edge of the text (right side in left-to-right text, left side in right-to-left text).

left

Align to the left.

right

Align to the right.

center

Align to the center.

The textBaseline attribute's allowed keywords correspond to alignment points in the font:

The top of the em square is roughly at the top of the glyphs in a font, the hanging baseline is where some glyphs like आ are anchored, the middle is half-way between the top of the em square and the bottom of the em square, the alphabetic baseline is where characters like Á, ÿ, f, and Ω are anchored, the ideographic-under baseline is where glyphs like 私 and 達 are anchored, and the bottom of the em square is roughly at the bottom of the glyphs in a font. The top and bottom of the bounding box can be far from these baselines, due to glyphs extending far outside the em square.

The keywords map to these alignment points as follows:

top
The top of the em square
hanging
The hanging baseline
middle
The middle of the em square
alphabetic
The alphabetic baseline
ideographic
The ideographic-under baseline
bottom
The bottom of the em square

The direction attribute's allowed keywords are as follows:

ltr

Treat input to the text preparation algorithm as left-to-right text.

rtl

Treat input to the text preparation algorithm as right-to-left text.

inherit

Default to the directionality of the canvas element or Document as appropriate.

The text preparation algorithm is as follows. It takes as input a string text , a CanvasTextDrawingStyles object target, and an optional length maxWidth. It returns an array of glyph shapes, each positioned on a common coordinate space, a physical alignment whose value is one of left, right, and center, and an inline box. (Most callers of this algorithm ignore the physical alignment and the inline box.)

  1. If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.

  2. Replace all ASCII whitespace in text with U+0020 SPACE characters.

  3. Let font be the current font of target, as given by that object's font attribute.

  4. Apply the appropriate step from the following list to determine the value of direction:

    If the target object's direction attribute has the value "ltr"
    Let direction be 'ltr'.
    If the target object's direction attribute has the value "rtl"
    Let direction be 'rtl'.
    If the target object's font style source object is an element
    Let direction be the directionality of the target object's font style source object.
    If the target object's font style source object is a Document with a non-null document element
    Let direction be the directionality of the target object's font style source object's document element.
    Otherwise
    Let direction be 'ltr'.
  5. Form a hypothetical infinitely-wide CSS line box containing a single inline box containing the text text, with all the properties at their initial values except the 'font' property of the inline box set to font, the 'direction' property of the inline box set to direction, and the 'white-space' property set to 'pre'. [CSS]

  6. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box is greater than maxWidth CSS pixels, then change font to have a more condensed font (if one is available or if a reasonably readable one can be synthesized by applying a horizontal scale factor to the font) or a smaller font, and return to the previous step.

  7. The anchor point is a point on the inline box, and the physical alignment is one of the values left, right, and center. These variables are determined by the textAlign and textBaseline values as follows:

    Horizontal position:

    If textAlign is left
    If textAlign is start and direction is 'ltr'
    If textAlign is end and direction is 'rtl'
    Let the anchor point's horizontal position be the left edge of the inline box, and let physical alignment be left.
    If textAlign is right
    If textAlign is end and direction is 'ltr'
    If textAlign is start and direction is 'rtl'
    Let the anchor point's horizontal position be the right edge of the inline box, and let physical alignment be right.
    If textAlign is center
    Let the anchor point's horizontal position be half way between the left and right edges of the inline box, and let physical alignment be center.

    Vertical position:

    If textBaseline is top
    Let the anchor point's vertical position be the top of the em box of the first available font of the inline box.
    If textBaseline is hanging
    Let the anchor point's vertical position be the hanging baseline of the first available font of the inline box.
    If textBaseline is middle
    Let the anchor point's vertical position be half way between the bottom and the top of the em box of the first available font of the inline box.
    If textBaseline is alphabetic
    Let the anchor point's vertical position be the alphabetic baseline of the first available font of the inline box.
    If textBaseline is ideographic
    Let the anchor point's vertical position be the ideographic-under baseline of the first available font of the inline box.
    If textBaseline is bottom
    Let the anchor point's vertical position be the bottom of the em box of the first available font of the inline box.
  8. Let result be an array constructed by iterating over each glyph in the inline box from left to right (if any), adding to the array, for each glyph, the shape of the glyph as it is in the inline box, positioned on a coordinate space using CSS pixels with its origin is at the anchor point.

  9. Return result, physical alignment, and the inline box.

4.12.5.1.5 Building paths

Objects that implement the CanvasPath interface have a path. A path has a list of zero or more subpaths. Each subpath consists of a list of one or more points, connected by straight or curved line segments, and a flag indicating whether the subpath is closed or not. A closed subpath is one where the last point of the subpath is connected to the first point of the subpath by a straight line. Subpaths with only one point are ignored when painting the path.

Paths have a need new subpath flag. When this flag is set, certain APIs create a new subpath rather than extending the previous one. When a path is created, its need new subpath flag must be set.

When an object implementing the CanvasPath interface is created, its path must be initialized to zero subpaths.

context . moveTo(x, y)

CanvasRenderingContext2D/moveTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . moveTo(x, y)

Creates a new subpath with the given point.

context . closePath()

CanvasRenderingContext2D/closePath

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . closePath()

Marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.

context . lineTo(x, y)

CanvasRenderingContext2D/lineTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . lineTo(x, y)

Adds the given point to the current subpath, connected to the previous one by a straight line.

context . quadraticCurveTo(cpx, cpy, x, y)

CanvasRenderingContext2D/quadraticCurveTo

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . quadraticCurveTo(cpx, cpy, x, y)

Adds the given point to the current subpath, connected to the previous one by a quadratic Bézier curve with the given control point.

context . bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

CanvasRenderingContext2D/bezierCurveTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Adds the given point to the current subpath, connected to the previous one by a cubic Bézier curve with the given control points.

context . arcTo(x1, y1, x2, y2, radius)

CanvasRenderingContext2D/arcTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . arcTo(x1, y1, x2, y2, radius)

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

Throws an "IndexSizeError" DOMException if the given radius is negative.

context . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] )

CanvasRenderingContext2D/arc

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] )

Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.

Throws an "IndexSizeError" DOMException if the given radius is negative.

context . ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] )

CanvasRenderingContext2D/ellipse

Support in all current engines.

Firefox48+Safari9+Chrome31+
Opera18+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android48+Safari iOS9+Chrome Android31+WebView Android4.4.3+Samsung Internet2.0+Opera Android18+
path . ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] )

Adds points to the subpath such that the arc described by the circumference of the ellipse described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.

Throws an "IndexSizeError" DOMException if the given radius is negative.

context . rect(x, y, w, h)

CanvasRenderingContext2D/rect

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . rect(x, y, w, h)

Adds a new closed subpath to the path, representing the given rectangle.

4.12.5.1.6 Path2D objects

Path2D

Support in all current engines.

Firefox31+Safari10+ChromeYes
OperaYesEdgeYes
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
caniuse.com table

Path2D objects can be used to declare paths that are then later used on objects implementing the CanvasDrawPath interface. In addition to many of the APIs described in earlier sections, Path2D objects have methods to combine paths, and to add text to paths.

path = new Path2D()

Path2D/Path2D

Support in all current engines.

Firefox31+Safari10+ChromeYes
OperaYesEdgeYes
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOSYesChrome Android42+WebView AndroidNoSamsung Internet4.0+Opera AndroidYes

Creates a new empty Path2D object.

path = new Path2D(path)

When path is a Path2D object, returns a copy.

When path is a string, creates the path described by the argument, interpreted as SVG path data. [SVG]

path . addPath(path [, transform ] )

Path2D/addPath

Support in all current engines.

Firefox34+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)NoInternet ExplorerNo
Firefox Android34+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Adds to the path the path given by the argument.

4.12.5.1.7 Transformations

Objects that implement the CanvasTransform interface have a current transformation matrix, as well as methods (described in this section) to manipulate it. When an object implementing the CanvasTransform interface is created, its transformation matrix must be initialized to the identity matrix.

The current transformation matrix is applied to coordinates when creating the current default path, and when painting text, shapes, and Path2D objects, on objects implementing the CanvasTransform interface.

context . scale(x, y)

CanvasRenderingContext2D/scale

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Changes the current transformation matrix to apply a scaling transformation with the given characteristics.

context . rotate(angle)

CanvasRenderingContext2D/rotate

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Changes the current transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.

context . translate(x, y)

CanvasRenderingContext2D/translate

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Changes the current transformation matrix to apply a translation transformation with the given characteristics.

context . transform(a, b, c, d, e, f)

CanvasRenderingContext2D/transform

Support in all current engines.

Firefox3+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Changes the current transformation matrix to apply the matrix given by the arguments as described below.

matrix = context . getTransform()

CanvasRenderingContext2D/getTransform

Support in all current engines.

Firefox70+Safari11+Chrome68+
Opera55+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11+Chrome Android68+WebView Android68+Samsung Internet10.0+Opera Android48+

Returns a copy of the current transformation matrix, as a newly created DOMMatrix object.

context . setTransform(a, b, c, d, e, f)

CanvasRenderingContext2D/setTransform

Support in all current engines.

Firefox3+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Changes the current transformation matrix to the matrix given by the arguments as described below.

context . setTransform(transform)

Changes the current transformation matrix to the matrix represented by the passed DOMMatrix2DInit dictionary.

context . resetTransform()

CanvasRenderingContext2D/resetTransform

Support in all current engines.

Firefox36+SafariYesChrome31+
OperaYesEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android36+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidNo

Changes the current transformation matrix to the identity matrix.

ace
bdf
001

The arguments a, b, c, d, e, and f are sometimes called m11, m12, m21, m22, dx, and dy or m11, m21, m12, m22, dx, and dy. Care ought to be taken in particular with the order of the second and third arguments (b and c) as their order varies from API to API and APIs sometimes use the notation m12/m21 and sometimes m21/m12 for those positions.

Given a matrix of the form created by the transform() and setTransform() methods, i.e.,

ace
bdf
001

the resulting transformed coordinates after transform matrix multiplication will be

xnew = a x + c y + e
ynew = b x + d y + f

4.12.5.1.8 Image sources for 2D rendering contexts

Some methods on the CanvasDrawImage and CanvasFillStrokeStyles interfaces take the union type CanvasImageSource as an argument.

This union type allows objects implementing any of the following interfaces to be used as image sources:

Although not formally specified as such, SVG image elements are expected to be implemented nearly identical to img elements. That is, SVG image elements share the fundamental concepts and features of img elements.

The ImageBitmap interface can be created from a number of other image-representing types, including ImageData.

To check the usability of the image argument, where image is a CanvasImageSource object, run these steps:

  1. Switch on image:

    HTMLOrSVGImageElement

    If image's current request's state is broken, then throw an "InvalidStateError" DOMException.

    If image is not fully decodable, then return bad.

    If image has an intrinsic width or intrinsic height (or both) equal to zero, then return bad.

    HTMLVideoElement

    If image's readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return bad.

    HTMLCanvasElement
    OffscreenCanvas

    If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.

    ImageBitmap

    If image's [[Detached]] internal slot value is set to true, then throw an "InvalidStateError" DOMException.

  2. Return good.

When a CanvasImageSource object represents an HTMLOrSVGImageElement, the element's image must be used as the source image.

Specifically, when a CanvasImageSource object represents an animated image in an HTMLOrSVGImageElement, the user agent must use the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation, when rendering the image for CanvasRenderingContext2D APIs.

When a CanvasImageSource object represents an HTMLVideoElement, then the frame at the current playback position when the method with the argument is invoked must be used as the source image when rendering the image for CanvasRenderingContext2D APIs, and the source image's dimensions must be the intrinsic width and intrinsic height of the media resource (i.e. after any aspect-ratio correction has been applied).

When a CanvasImageSource object represents an HTMLCanvasElement, the element's bitmap must be used as the source image.

When a CanvasImageSource object represents an element that is being rendered and that element has been resized, the original image data of the source image must be used, not the image as it is rendered (e.g. width and height attributes on the source element have no effect on how the object is interpreted when rendering the image for CanvasRenderingContext2D APIs).

When a CanvasImageSource object represents an ImageBitmap, the object's bitmap image data must be used as the source image.

An object image is not origin-clean if, switching on image:

HTMLOrSVGImageElement
HTMLVideoElement

image's origin is not same origin with entry settings object's origin.

HTMLCanvasElement
ImageBitMap

image's bitmap's origin-clean flag is false.

4.12.5.1.9 Fill and stroke styles
context . fillStyle [ = value ]

CanvasRenderingContext2D/fillStyle

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the current style used for filling shapes.

Can be set, to change the fill style.

The style can be either a string containing a CSS color, or a CanvasGradient or CanvasPattern object. Invalid values are ignored.

context . strokeStyle [ = value ]

CanvasRenderingContext2D/strokeStyle

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the current style used for stroking shapes.

Can be set, to change the stroke style.

The style can be either a string containing a CSS color, or a CanvasGradient or CanvasPattern object. Invalid values are ignored.


There are two types of gradients, linear gradients and radial gradients, both represented by objects implementing the opaque CanvasGradient interface.

Once a gradient has been created (see below), stops are placed along it to define how the colors are distributed along the gradient.

gradient . addColorStop(offset, color)

CanvasGradient/addColorStop

Support in all current engines.

Firefox3.6+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.

Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed.

gradient = context . createLinearGradient(x0, y0, x1, y1)

CanvasRenderingContext2D/createLinearGradient

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns a CanvasGradient object that represents a linear gradient that paints along the line given by the coordinates represented by the arguments.

gradient = context . createRadialGradient(x0, y0, r0, x1, y1, r1)

CanvasRenderingContext2D/createRadialGradient

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments.

If either of the radii are negative, throws an "IndexSizeError" DOMException exception.


Patterns are represented by objects implementing the opaque CanvasPattern interface.

pattern = context . createPattern(image, repetition)

CanvasRenderingContext2D/createPattern

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns a CanvasPattern object that uses the given image and repeats in the direction(s) given by the repetition argument.

The allowed values for repetition are repeat (both directions), repeat-x (horizontal only), repeat-y (vertical only), and no-repeat (neither). If the repetition argument is empty, the value repeat is used.

If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no data, throws an "InvalidStateError" DOMException.

pattern . setTransform(transform)

CanvasPattern/setTransform

Support in all current engines.

Firefox33+Safari3.1+Chrome68+
Opera9+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS11+Chrome Android68+WebView Android68+Samsung Internet10.0+Opera Android10.1+

Sets the transformation matrix that will be used when rendering the pattern during a fill or stroke painting operation.

4.12.5.1.10 Drawing rectangles to the bitmap

Objects that implement the CanvasRect interface provide the following methods for immediately drawing rectangles to the bitmap. The methods each take four arguments; the first two give the x and y coordinates of the top left of the rectangle, and the second two give the width w and height h of the rectangle, respectively.

context . clearRect(x, y, w, h)

CanvasRenderingContext2D/clearRect

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Clears all pixels on the bitmap in the given rectangle to transparent black.

context . fillRect(x, y, w, h)

CanvasRenderingContext2D/fillRect

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Paints the given rectangle onto the bitmap, using the current fill style.

context . strokeRect(x, y, w, h)

CanvasRenderingContext2D/strokeRect

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Paints the box that outlines the given rectangle onto the bitmap, using the current stroke style.

4.12.5.1.11 Drawing text to the bitmap

CanvasRenderingContext2D

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
caniuse.com table
context . fillText(text, x, y [, maxWidth ] )

CanvasRenderingContext2D/fillText

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . strokeText(text, x, y [, maxWidth ] )

CanvasRenderingContext2D/strokeText

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Fills or strokes (respectively) the given text at the given position. If a maximum width is provided, the text will be scaled to fit that width if necessary.

metrics = context . measureText(text)

CanvasRenderingContext2D/measureText

Support in all current engines.

Firefox2+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns a TextMetrics object with the metrics of the given text in the current font.

metrics . width

TextMetrics/width

Support in all current engines.

Firefox1.5+Safari3.1+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android31+Safari iOS3.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
metrics . actualBoundingBoxLeft

TextMetrics/actualBoundingBoxLeft

Support in all current engines.

Firefox74+SafariYesChrome77+
Opera?Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android?
metrics . actualBoundingBoxRight

TextMetrics/actualBoundingBoxRight

Support in all current engines.

Firefox74+SafariYesChrome77+
Opera?Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android?
metrics . fontBoundingBoxAscent

TextMetrics/fontBoundingBoxAscent

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?
metrics . fontBoundingBoxDescent

TextMetrics/fontBoundingBoxDescent

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?
metrics . actualBoundingBoxAscent

TextMetrics/actualBoundingBoxAscent

Support in all current engines.

Firefox74+SafariYesChrome77+
Opera?Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android?
metrics . actualBoundingBoxDescent

TextMetrics/actualBoundingBoxDescent

Support in all current engines.

Firefox74+SafariYesChrome77+
Opera?Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android?
metrics . emHeightAscent

TextMetrics/emHeightAscent

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?
metrics . emHeightDescent

TextMetrics/emHeightDescent

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?
metrics . hangingBaseline

TextMetrics/hangingBaseline

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?
metrics . alphabeticBaseline

TextMetrics/alphabeticBaseline

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?
metrics . ideographicBaseline

TextMetrics/ideographicBaseline

Support in all current engines.

Firefox🔰 74+SafariYesChrome🔰 Yes
Opera?Edge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSYesChrome Android🔰 YesWebView AndroidNoSamsung InternetNoOpera Android?

Returns the measurement described below.

width attribute

The width of that inline box, in CSS pixels. (The text's advance width.)

actualBoundingBoxLeft attribute

The distance parallel to the baseline from the alignment point given by the textAlign attribute to the left side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going left from the given alignment point.

The sum of this value and the next (actualBoundingBoxRight) can be wider than the width of the inline box (width), in particular with slanted fonts where characters overhang their advance width.

actualBoundingBoxRight attribute

The distance parallel to the baseline from the alignment point given by the textAlign attribute to the right side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going right from the given alignment point.

fontBoundingBoxAscent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the ascent metric of the first available font, in CSS pixels; positive numbers indicating a distance going up from the given baseline.

This value and the next are useful when rendering a background that have to have a consistent height even if the exact text being rendered changes. The actualBoundingBoxAscent attribute (and its corresponding attribute for the descent) are useful when drawing a bounding box around specific text.

fontBoundingBoxDescent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the descent metric of the first available font, in CSS pixels; positive numbers indicating a distance going down from the given baseline.

actualBoundingBoxAscent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the top of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going up from the given baseline.

This number can vary greatly based on the input text, even if the first font specified covers all the characters in the input. For example, the actualBoundingBoxAscent of a lowercase "o" from an alphabetic baseline would be less than that of an uppercase "F". The value can easily be negative; for example, the distance from the top of the em box (textBaseline value "top") to the top of the bounding rectangle when the given text is just a single comma "," would likely (unless the font is quite unusual) be negative.

actualBoundingBoxDescent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going down from the given baseline.

emHeightAscent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the highest top of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the top of that em square (so this value will usually be positive). Zero if the given baseline is the top of that em square; half the font size if the given baseline is the middle of that em square.

emHeightDescent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the lowest bottom of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is above the bottom of that em square. (Zero if the given baseline is the bottom of that em square.)

hangingBaseline attribute

The distance from the horizontal line indicated by the textBaseline attribute to the hanging baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the hanging baseline. (Zero if the given baseline is the hanging baseline.)

alphabeticBaseline attribute

The distance from the horizontal line indicated by the textBaseline attribute to the alphabetic baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the alphabetic baseline. (Zero if the given baseline is the alphabetic baseline.)

ideographicBaseline attribute

The distance from the horizontal line indicated by the textBaseline attribute to the ideographic-under baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the ideographic-under baseline. (Zero if the given baseline is the ideographic-under baseline.)

Glyphs rendered using fillText() and strokeText() can spill out of the box given by the font size (the em square size) and the width returned by measureText() (the text width). Authors are encouraged to use the bounding box values described above if this is an issue.

A future version of the 2D context API might provide a way to render fragments of documents, rendered using CSS, straight to the canvas. This would be provided in preference to a dedicated way of doing multiline layout.

4.12.5.1.12 Drawing paths to the canvas

Objects that implement the CanvasDrawPath interface have a current default path. There is only one current default path, it is not part of the drawing state. The current default path is a path, as described above.

context . beginPath()

CanvasRenderingContext2D/beginPath

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Resets the current default path.

context . fill( [ fillRule ] )

CanvasRenderingContext2D/fill

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . fill(path [, fillRule ] )

Fills the subpaths of the current default path or the given path with the current fill style, obeying the given fill rule.

context . stroke()

CanvasRenderingContext2D/stroke

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . stroke(path)

Strokes the subpaths of the current default path or the given path with the current stroke style.

context . clip( [ fillRule ] )

CanvasRenderingContext2D/clip

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . clip(path [, fillRule ] )

Further constrains the clipping region to the current default path or the given path, using the given fill rule to determine what points are in the path.

context . isPointInPath(x, y [, fillRule ] )

CanvasRenderingContext2D/isPointInPath

Support in all current engines.

Firefox2+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . isPointInPath(path, x, y [, fillRule ] )

Returns true if the given point is in the current default path or the given path, using the given fill rule to determine what points are in the path.

context . isPointInStroke(x, y)

CanvasRenderingContext2D/isPointInStroke

Support in all current engines.

Firefox20+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)NoInternet ExplorerNo
Firefox Android20+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . isPointInStroke(path, x, y)

Returns true if the given point would be in the region covered by the stroke of the current default path or the given path, given the current stroke style.

This canvas element has a couple of checkboxes. The path-related commands are highlighted:

<canvas height=400 width=750>
 <label><input type=checkbox id=showA> Show As</label>
 <label><input type=checkbox id=showB> Show Bs</label>
 <!-- ... -->
</canvas>
<script>
 function drawCheckbox(context, element, x, y, paint) {
   context.save();
   context.font = '10px sans-serif';
   context.textAlign = 'left';
   context.textBaseline = 'middle';
   var metrics = context.measureText(element.labels[0].textContent);
   if (paint) {
     context.beginPath();
     context.strokeStyle = 'black';
     context.rect(x-5, y-5, 10, 10);
     context.stroke();
     if (element.checked) {
       context.fillStyle = 'black';
       context.fill();
     }
     context.fillText(element.labels[0].textContent, x+5, y);
   }
   context.beginPath();
   context.rect(x-7, y-7, 12 + metrics.width+2, 14);

   context.drawFocusIfNeeded(element);
   context.restore();
 }
 function drawBase() { /* ... */ }
 function drawAs() { /* ... */ }
 function drawBs() { /* ... */ }
 function redraw() {
   var canvas = document.getElementsByTagName('canvas')[0];
   var context = canvas.getContext('2d');
   context.clearRect(0, 0, canvas.width, canvas.height);
   drawCheckbox(context, document.getElementById('showA'), 20, 40, true);
   drawCheckbox(context, document.getElementById('showB'), 20, 60, true);
   drawBase();
   if (document.getElementById('showA').checked)
     drawAs();
   if (document.getElementById('showB').checked)
     drawBs();
 }
 function processClick(event) {
   var canvas = document.getElementsByTagName('canvas')[0];
   var context = canvas.getContext('2d');
   var x = event.clientX;
   var y = event.clientY;
   var node = event.target;
   while (node) {
     x -= node.offsetLeft - node.scrollLeft;
     y -= node.offsetTop - node.scrollTop;
     node = node.offsetParent;
   }
   drawCheckbox(context, document.getElementById('showA'), 20, 40, false);
   if (context.isPointInPath(x, y))
     document.getElementById('showA').checked = !(document.getElementById('showA').checked);
   drawCheckbox(context, document.getElementById('showB'), 20, 60, false);
   if (context.isPointInPath(x, y))
     document.getElementById('showB').checked = !(document.getElementById('showB').checked);
   redraw();
 }
 document.getElementsByTagName('canvas')[0].addEventListener('focus', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('blur', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('change', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('click', processClick, false);
 redraw();
</script>
4.12.5.1.13 Drawing focus rings and scrolling paths into view
context . drawFocusIfNeeded(element)

CanvasRenderingContext2D/drawFocusIfNeeded

Support in all current engines.

Firefox32+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)14+Internet ExplorerNo
Firefox Android32+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . drawFocusIfNeeded(path, element)

If the given element is focused, draws a focus ring around the current default path or the given path, following the platform conventions for focus rings.

context . scrollPathIntoView()

CanvasRenderingContext2D/scrollPathIntoView

Support in one engine only.

FirefoxNoSafariNoChrome🔰 Yes
OperaYesEdge🔰 Yes
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidNo
context . scrollPathIntoView(path)

Scrolls the current default path or the given path into view. This is especially useful on devices with small screens, where the whole canvas might not be visible at once.

4.12.5.1.14 Drawing images

CanvasRenderingContext2D/drawImage

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Objects that implement the CanvasDrawImage interface have the drawImage method to draw images.

context . drawImage(image, dx, dy)
context . drawImage(image, dx, dy, dw, dh)
context . drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

Draws the given image onto the canvas. The arguments are interpreted as follows:

The sx and sy parameters give the x and y coordinates of the source rectangle; the sw and sh arguments give the width and height of the source rectangle; the dx and dy give the x and y coordinates of the destination rectangle; and the dw and dh arguments give the width and height of the destination rectangle.

If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no data, throws an "InvalidStateError" DOMException.

4.12.5.1.15 Pixel manipulation
imagedata = new ImageData(sw, sh)

ImageData/ImageData

Firefox29+Safari?Chrome42+
Opera29+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android29+Safari iOS?Chrome Android42+WebView AndroidNoSamsung Internet4.0+Opera Android?
imagedata = context . createImageData(sw, sh)

CanvasRenderingContext2D/createImageData

Support in all current engines.

Firefox2+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns an ImageData object with the given dimensions. All the pixels in the returned object are transparent black.

Throws an "IndexSizeError" DOMException if either of the width or height arguments are zero.

imagedata = context . createImageData(imagedata)

Returns an ImageData object with the same dimensions as the argument. All the pixels in the returned object are transparent black.

imagedata = new ImageData(data, sw [, sh ] )

Returns an ImageData object using the data provided in the Uint8ClampedArray argument, interpreted using the given dimensions.

As each pixel in the data is represented by four numbers, the length of the data needs to be a multiple of four times the given width. If the height is provided as well, then the length needs to be exactly the width times the height times 4.

Throws an "IndexSizeError" DOMException if the given data and dimensions can't be interpreted consistently, or if either dimension is zero.

imagedata = context . getImageData(sx, sy, sw, sh)

CanvasRenderingContext2D/getImageData

Support in all current engines.

Firefox2+Safari4+Chrome1+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns an ImageData object containing the image data for the given rectangle of the bitmap.

Throws an "IndexSizeError" DOMException if the either of the width or height arguments are zero.

imagedata . width

ImageData/width

Support in all current engines.

Firefox14+Safari3.1+ChromeYes
Opera9+EdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android14+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
imagedata . height

ImageData/height

Support in all current engines.

Firefox14+Safari3.1+ChromeYes
Opera9+EdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android14+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the actual dimensions of the data in the ImageData object, in pixels.

imagedata . data

ImageData/data

Support in all current engines.

Firefox14+Safari3.1+ChromeYes
Opera9+EdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android14+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.

context . putImageData(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ] )

CanvasRenderingContext2D/putImageData

Support in all current engines.

Firefox2+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

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

The globalAlpha and globalCompositeOperation attributes, as well as the shadow attributes, are ignored for the purposes of this method call; pixels in the canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.

Throws an "InvalidStateError" DOMException if the imagedata object's data attribute value's [[ViewedArrayBuffer]] internal slot is detached.

In the following example, the script generates an ImageData object so that it can draw onto it.

// canvas is a reference to a <canvas> element
var context = canvas.getContext('2d');

// create a blank slate
var data = context.createImageData(canvas.width, canvas.height);

// create some plasma
FillPlasma(data, 'green'); // green plasma

// add a cloud to the plasma
AddCloud(data, data.width/2, data.height/2); // put a cloud in the middle

// paint the plasma+cloud on the canvas
context.putImageData(data, 0, 0);

// support methods
function FillPlasma(data, color) { ... }
function AddCloud(data, x, y) { ... }

Here is an example of using getImageData() and putImageData() to implement an edge detection filter.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Edge detection demo</title>
  <script>
   var image = new Image();
   function init() {
     image.onload = demo;
     image.src = "image.jpeg";
   }
   function demo() {
     var canvas = document.getElementsByTagName('canvas')[0];
     var context = canvas.getContext('2d');

     // draw the image onto the canvas
     context.drawImage(image, 0, 0);

     // get the image data to manipulate
     var input = context.getImageData(0, 0, canvas.width, canvas.height);

     // get an empty slate to put the data into
     var output = context.createImageData(canvas.width, canvas.height);

     // alias some variables for convenience
     // In this case input.width and input.height
     // match canvas.width and canvas.height
     // but we'll use the former to keep the code generic.
     var w = input.width, h = input.height;
     var inputData = input.data;
     var outputData = output.data;

     // edge detection
     for (var y = 1; y < h-1; y += 1) {
       for (var x = 1; x < w-1; x += 1) {
         for (var c = 0; c < 3; c += 1) {
           var i = (y*w + x)*4 + c;
           outputData[i] = 127 + -inputData[i - w*4 - 4] -   inputData[i - w*4] - inputData[i - w*4 + 4] +
                                 -inputData[i - 4]       + 8*inputData[i]       - inputData[i + 4] +
                                 -inputData[i + w*4 - 4] -   inputData[i + w*4] - inputData[i + w*4 + 4];
         }
         outputData[(y*w + x)*4 + 3] = 255; // alpha
       }
     }

     // put the image data back after manipulation
     context.putImageData(output, 0, 0);
   }
  </script>
 </head>
 <body onload="init()">
  <canvas></canvas>
 </body>
</html>
4.12.5.1.16 Compositing
context . globalAlpha [ = value ]

CanvasRenderingContext2D/globalAlpha

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the current alpha value applied to rendering operations.

Can be set, to change the alpha value. Values outside of the range 0.0 .. 1.0 are ignored.

context . globalCompositeOperation [ = value ]

CanvasRenderingContext2D/globalCompositeOperation

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns the current composition operation, from the values defined in Compositing and Blending. [COMPOSITE].

Can be set, to change the composition operation. Unknown values are ignored.

4.12.5.1.17 Image smoothing
context . imageSmoothingEnabled [ = value ]

CanvasRenderingContext2D/imageSmoothingEnabled

Support in all current engines.

Firefox51+SafariYesChrome30+
OperaYesEdge79+
Edge (Legacy)15+Internet Explorer🔰 Yes
Firefox Android51+Safari iOSYesChrome AndroidYesWebView Android4.4+Samsung InternetYesOpera AndroidYes

Returns whether pattern fills and the drawImage() method will attempt to smooth images if their pixels don't line up exactly with the display, when scaling images up.

Can be set, to change whether images are smoothed (true) or not (false).

context . imageSmoothingQuality [ = value ]

Returns the current image-smoothing-quality preference.

Can be set, to change the preferred quality of image smoothing. The possible values are "low", "medium" and "high". Unknown values are ignored.

4.12.5.1.18 Shadows

All drawing operations on an object which implements the CanvasShadowStyles interface are affected by the four global shadow attributes.

context . shadowColor [ = value ]

CanvasRenderingContext2D/shadowColor

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the current shadow color.

Can be set, to change the shadow color. Values that cannot be parsed as CSS colors are ignored.

context . shadowOffsetX [ = value ]

CanvasRenderingContext2D/shadowOffsetX

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
context . shadowOffsetY [ = value ]

CanvasRenderingContext2D/shadowOffsetY

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the current shadow offset.

Can be set, to change the shadow offset. Values that are not finite numbers are ignored.

context . shadowBlur [ = value ]

CanvasRenderingContext2D/shadowBlur

Support in all current engines.

Firefox1.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Returns the current level of blur applied to shadows.

Can be set, to change the blur level. Values that are not finite numbers greater than or equal to zero are ignored.

If the current composition operation is copy, then shadows effectively won't render (since the shape will overwrite the shadow).

4.12.5.1.19 Filters

CanvasRenderingContext2D/filter

Firefox49+SafariNoChrome52+
OperaNoEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOSNoChrome Android52+WebView Android52+Samsung Internet6.0+Opera AndroidNo

All drawing operations on an object which implements the CanvasFilters interface are affected by the global filter attribute.

context . filter [ = value ]

Returns the current filter.

Can be set, to change the filter. Values that cannot be parsed as a <filter-function-list> value are ignored.

4.12.5.1.20 Working with externally-defined SVG filters

Since drawing is performed using filter value 'none' until an externally-defined filter has finished loading, authors might wish to determine whether such a filter has finished loading before proceeding with a drawing operation. One way to accomplish this is to load the externally-defined filter elsewhere within the same page in some element that sends a load event (for example, an SVG use element), and wait for the load event to be dispatched.

4.12.5.1.21 Best practices

When a canvas is interactive, authors should include focusable elements in the element's fallback content corresponding to each focusable part of the canvas, as in the example above.

When rendering focus rings, to ensure that focus rings have the appearance of native focus rings, authors should use the drawFocusIfNeeded() method, passing it the element for which a ring is being drawn. This method only draws the focus ring if the element is focused, so that it can simply be called whenever drawing the element, without checking whether the element is focused or not first.

In addition to drawing focus rings, authors should use the scrollPathIntoView() method when an element in the canvas is focused, to make sure it is visible on the screen (if applicable).

Authors should avoid implementing text editing controls using the canvas element. Doing so has a large number of disadvantages:

This is a huge amount of work, and authors are most strongly encouraged to avoid doing any of it by instead using the input element, the textarea element, or the contenteditable attribute.

4.12.5.1.22 Examples

Here is an example of a script that uses canvas to draw pretty glowing lines.

<canvas width="800" height="450"></canvas>
<script>

 var context = document.getElementsByTagName('canvas')[0].getContext('2d');

 var lastX = context.canvas.width * Math.random();
 var lastY = context.canvas.height * Math.random();
 var hue = 0;
 function line() {
   context.save();
   context.translate(context.canvas.width/2, context.canvas.height/2);
   context.scale(0.9, 0.9);
   context.translate(-context.canvas.width/2, -context.canvas.height/2);
   context.beginPath();
   context.lineWidth = 5 + Math.random() * 10;
   context.moveTo(lastX, lastY);
   lastX = context.canvas.width * Math.random();
   lastY = context.canvas.height * Math.random();
   context.bezierCurveTo(context.canvas.width * Math.random(),
                         context.canvas.height * Math.random(),
                         context.canvas.width * Math.random(),
                         context.canvas.height * Math.random(),
                         lastX, lastY);

   hue = hue + 10 * Math.random();
   context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';
   context.shadowColor = 'white';
   context.shadowBlur = 10;
   context.stroke();
   context.restore();
 }
 setInterval(line, 50);

 function blank() {
   context.fillStyle = 'rgba(0,0,0,0.1)';
   context.fillRect(0, 0, context.canvas.width, context.canvas.height);
 }
 setInterval(blank, 40);

</script>

The 2D rendering context for canvas is often used for sprite-based games. The following example demonstrates this:

Here is the source for this example:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Blue Robot Demo</title>
<style>
  html { overflow: hidden; min-height: 200px; min-width: 380px; }
  body { height: 200px; position: relative; margin: 8px; }
  .buttons { position: absolute; bottom: 0px; left: 0px; margin: 4px; }
</style>
<canvas width="380" height="200"></canvas>
<script>
 var Landscape = function (context, width, height) {
   this.offset = 0;
   this.width = width;
   this.advance = function (dx) {
     this.offset += dx;
   };
   this.horizon = height * 0.7;
   // This creates the sky gradient (from a darker blue to white at the bottom)
   this.sky = context.createLinearGradient(0, 0, 0, this.horizon);
   this.sky.addColorStop(0.0, 'rgb(55,121,179)');
   this.sky.addColorStop(0.7, 'rgb(121,194,245)');
   this.sky.addColorStop(1.0, 'rgb(164,200,214)');
   // this creates the grass gradient (from a darker green to a lighter green)
   this.earth = context.createLinearGradient(0, this.horizon, 0, height);
   this.earth.addColorStop(0.0, 'rgb(81,140,20)');
   this.earth.addColorStop(1.0, 'rgb(123,177,57)');
   this.paintBackground = function (context, width, height) {
     // first, paint the sky and grass rectangles
     context.fillStyle = this.sky;
     context.fillRect(0, 0, width, this.horizon);
     context.fillStyle = this.earth;
     context.fillRect(0, this.horizon, width, height-this.horizon);
     // then, draw the cloudy banner
     // we make it cloudy by having the draw text off the top of the
     // canvas, and just having the blurred shadow shown on the canvas
     context.save();
     context.translate(width-((this.offset+(this.width*3.2)) % (this.width*4.0))+0, 0);
     context.shadowColor = 'white';
     context.shadowOffsetY = 30+this.horizon/3; // offset down on canvas
     context.shadowBlur = '5';
     context.fillStyle = 'white';
     context.textAlign = 'left';
     context.textBaseline = 'top';
     context.font = '20px sans-serif';
     context.fillText('WHATWG ROCKS', 10, -30); // text up above canvas
     context.restore();
     // then, draw the background tree
     context.save();
     context.translate(width-((this.offset+(this.width*0.2)) % (this.width*1.5))+30, 0);
     context.beginPath();
     context.fillStyle = 'rgb(143,89,2)';
     context.lineStyle = 'rgb(10,10,10)';
     context.lineWidth = 2;
     context.rect(0, this.horizon+5, 10, -50); // trunk
     context.fill();
     context.stroke();
     context.beginPath();
     context.fillStyle = 'rgb(78,154,6)';
     context.arc(5, this.horizon-60, 30, 0, Math.PI*2); // leaves
     context.fill();
     context.stroke();
     context.restore();
   };
   this.paintForeground = function (context, width, height) {
     // draw the box that goes in front
     context.save();
     context.translate(width-((this.offset+(this.width*0.7)) % (this.width*1.1))+0, 0);
     context.beginPath();
     context.rect(0, this.horizon - 5, 25, 25);
     context.fillStyle = 'rgb(220,154,94)';
     context.lineStyle = 'rgb(10,10,10)';
     context.lineWidth = 2;
     context.fill();
     context.stroke();
     context.restore();
   };
 };
</script>
<script>
 var BlueRobot = function () {
   this.sprites = new Image();
   this.sprites.src = 'blue-robot.png'; // this sprite sheet has 8 cells
   this.targetMode = 'idle';
   this.walk = function () {
     this.targetMode = 'walk';
   };
   this.stop = function () {
     this.targetMode = 'idle';
   };
   this.frameIndex = {
     'idle': [0], // first cell is the idle frame
     'walk': [1,2,3,4,5,6], // the walking animation is cells 1-6
     'stop': [7], // last cell is the stopping animation
   };
   this.mode = 'idle';
   this.frame = 0; // index into frameIndex
   this.tick = function () {
     // this advances the frame and the robot
     // the return value is how many pixels the robot has moved
     this.frame += 1;
     if (this.frame >= this.frameIndex[this.mode].length) {
       // we've reached the end of this animation cycle
       this.frame = 0;
       if (this.mode != this.targetMode) {
         // switch to next cycle
         if (this.mode == 'walk') {
           // we need to stop walking before we decide what to do next
           this.mode = 'stop';
         } else if (this.mode == 'stop') {
           if (this.targetMode == 'walk')
             this.mode = 'walk';
           else
             this.mode = 'idle';
         } else if (this.mode == 'idle') {
           if (this.targetMode == 'walk')
             this.mode = 'walk';
         }
       }
     }
     if (this.mode == 'walk')
       return 8;
     return 0;
   },
   this.paint = function (context, x, y) {
     if (!this.sprites.complete) return;
     // draw the right frame out of the sprite sheet onto the canvas
     // we assume each frame is as high as the sprite sheet
     // the x,y coordinates give the position of the bottom center of the sprite
     context.drawImage(this.sprites,
                       this.frameIndex[this.mode][this.frame] * this.sprites.height, 0, this.sprites.height, this.sprites.height,
                       x-this.sprites.height/2, y-this.sprites.height, this.sprites.height, this.sprites.height);
   };
 };
</script>
<script>
 var canvas = document.getElementsByTagName('canvas')[0];
 var context = canvas.getContext('2d');
 var landscape = new Landscape(context, canvas.width, canvas.height);
 var blueRobot = new BlueRobot();
 // paint when the browser wants us to, using requestAnimationFrame()
 function paint() {
   context.clearRect(0, 0, canvas.width, canvas.height);
   landscape.paintBackground(context, canvas.width, canvas.height);
   blueRobot.paint(context, canvas.width/2, landscape.horizon*1.1);
   landscape.paintForeground(context, canvas.width, canvas.height);
   requestAnimationFrame(paint);
 }
 paint();
 // but tick every 100ms, so that we don't slow down when we don't paint
 setInterval(function () {
   var dx = blueRobot.tick();
   landscape.advance(dx);
 }, 100);
</script>
<p class="buttons">
 <input type=button value="Walk" onclick="blueRobot.walk()">
 <input type=button value="Stop" onclick="blueRobot.stop()">
<footer>
 <small> Blue Robot Player Sprite by <a href="https://johncolburn.deviantart.com/">JohnColburn</a>.
 Licensed under the terms of the Creative Commons Attribution Share-Alike 3.0 Unported license.</small>
 <small> This work is itself licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/3.0/">Creative
 Commons Attribution-ShareAlike 3.0 Unported License</a>.</small>
</footer>
4.12.5.2 The ImageBitmap rendering context
4.12.5.2.1 Introduction

ImageBitmapRenderingContext is a performance-oriented interface that provides a low overhead method for displaying the contents of ImageBitmap objects. It uses transfer semantics to reduce overall memory consumption. It also streamlines performance by avoiding intermediate compositing, unlike the drawImage() method of CanvasRenderingContext2D.

Using an img element as an intermediate for getting an image resource into a canvas, for example, would result in two copies of the decoded image existing in memory at the same time: the img element's copy, and the one in the canvas's backing store. This memory cost can be prohibitive when dealing with extremely large images. This can be avoided by using ImageBitmapRenderingContext.

Using ImageBitmapRenderingContext, here is how to transcode an image to the JPEG format in a memory- and CPU-efficient way:

createImageBitmap(inputImageBlob).then(image => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('bitmaprenderer');
  context.transferFromImageBitmap(image);

  canvas.toBlob(outputJPEGBlob => {
    // Do something with outputJPEGBlob.
  }, 'image/jpeg');
});
4.12.5.2.2 The ImageBitmapRenderingContext interface

ImageBitmapRenderingContext

Firefox46+SafariNoChrome66+
OperaYesEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android46+Safari iOS?Chrome Android66+WebView Android66+Samsung Internet9.0+Opera AndroidYes
context = canvas . getContext('bitmaprenderer' [, { [ alpha: false ] } ] )

Returns an ImageBitmapRenderingContext object that is permanently bound to a particular canvas element.

If the alpha setting is provided and set to false, then the canvas is forced to always be opaque.

context . canvas

Returns the canvas element that the context is bound to.

context . transferFromImageBitmap(imageBitmap)

ImageBitmapRenderingContext/transferFromImageBitmap

Firefox52+SafariNoChrome66+
OperaYesEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android52+Safari iOS?Chrome Android66+WebView Android66+Samsung Internet9.0+Opera AndroidYes

Transfers the underlying bitmap data from imageBitmap to context, and the bitmap becomes the contents of the canvas element to which context is bound.

context . transferFromImageBitmap(null)

Replaces contents of the canvas element to which context is bound with a transparent black bitmap whose size corresponds to the width and height content attributes of the canvas element.

4.12.5.3 The OffscreenCanvas interface

OffscreenCanvas

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 44+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera Android48+
caniuse.com table

OffscreenCanvas is an EventTarget so that WebGL can fire webglcontextlost and webglcontextrestored events at it. [WEBGL]

OffscreenCanvas objects are used to create rendering contexts, much like an HTMLCanvasElement, but with no connection to the DOM. This makes it possible to use canvas rendering contexts in workers.

WebGLRenderingContext/commit

Support in one engine only.

Firefox🔰 44+SafariNoChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

An OffscreenCanvas object may hold a weak reference to a placeholder canvas element, which is typically in the DOM, whose embedded content is provided by the OffscreenCanvas object. The bitmap of the OffscreenCanvas object is pushed to the placeholder canvas element by calling the commit() method of the OffscreenCanvas object's rendering context. All rendering context types that can be created by an OffscreenCanvas object must implement a commit() method. The exact behavior of the commit method (e.g. whether it copies or transfers bitmaps) may vary, as defined by the rendering contexts' respective specifications. Only the 2D context for offscreen canvases is defined in this specification.

offscreenCanvas = new OffscreenCanvas(width, height)

OffscreenCanvas/OffscreenCanvas

Support in one engine only.

Firefox🔰 46+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 46+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera AndroidYes

Returns a new OffscreenCanvas object that is not linked to a placeholder canvas element, and whose bitmap's size is determined by the width and height arguments.

context = offscreenCanvas . getContext(contextId [, options ] )

OffscreenCanvas/getContext

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 44+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera Android48+

Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API.

This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL]

Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context).

offscreenCanvas . width [ = value ]

OffscreenCanvas/width

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 44+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera Android48+
offscreenCanvas . height [ = value ]

OffscreenCanvas/height

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 44+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera Android48+

These attributes return the dimensions of the OffscreenCanvas object's bitmap.

They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it).

If an OffscreenCanvas object whose dimensions were changed has a placeholder canvas element, then the placeholder canvas element's intrinsic size will only be updated via the commit() method of the OffscreenCanvas object's rendering context.

promise = offscreenCanvas . convertToBlob( [options] )

OffscreenCanvas/convertToBlob

Support in one engine only.

Firefox🔰 46+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 46+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera Android48+

Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object.

The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of "image/png"; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as "image/jpeg"), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image.

canvas . transferToImageBitmap()

OffscreenCanvas/transferToImageBitmap

Support in one engine only.

Firefox🔰 46+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 46+Safari iOSNoChrome Android69+WebView AndroidNoSamsung Internet10.0+Opera Android48+

Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image.

4.12.5.3.1 The offscreen 2D rendering context

The OffscreenCanvasRenderingContext2D object is a rendering context for drawing to the bitmap of an OffscreenCanvas object. It is similar to the CanvasRenderingContext2D object, with the following differences:

An OffscreenCanvasRenderingContext2D object has a bitmap that is initialized when the object is created.

The bitmap has an origin-clean flag, which can be set to true or false. Initially, when one of these bitmaps is created, its origin-clean flag must be set to true.

An OffscreenCanvasRenderingContext2D object also has an alpha flag, which can be set to true or false. Initially, when the context is created, its alpha flag must be set to true. When an OffscreenCanvasRenderingContext2D object has its alpha flag set to false, then its alpha channel must be fixed to 1.0 (fully opaque) for all pixels, and attempts to change the alpha component of any pixel must be silently ignored.

An OffscreenCanvasRenderingContext2D object has an associated OffscreenCanvas object, which is the OffscreenCanvas object from which the OffscreenCanvasRenderingContext2D object was created.

offscreenCanvasRenderingContext2D . commit()

Copies the rendering context's bitmap to the bitmap of the placeholder canvas element of the associated OffscreenCanvas object. The copy operation is synchronous. Calling this method is not needed for the transfer, since it happens automatically during the event loop execution.

offscreenCanvas = offscreenCanvasRenderingContext2D . canvas

Returns the associated OffscreenCanvas object.

4.12.5.4 Serializing bitmaps to a file