4.8.11
The canvas element
- 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
aelements,buttonelements,inputelements whosetypeattribute are in the Checkbox or Radio Button states, andinputelements that are buttons. - Content attributes:
- Global attributes
widthheight- DOM interface:
-
typedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext; interface HTMLCanvasElement : HTMLElement { attribute unsigned long width; attribute unsigned long height; RenderingContext? getContext(DOMString contextId, any... arguments); boolean supportsContext(DOMString contextId, any... arguments); void setContext(RenderingContext context); CanvasProxy transferControlToProxy(); DOMString toDataURL(optional DOMString type, any... arguments); DOMString toDataURLHD(optional DOMString type, any... arguments); void toBlob(FileCallback? _callback, optional DOMString type, any... arguments); void toBlobHD(FileCallback? _callback, optional DOMString type, any... arguments); };
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 XBL.
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' 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,
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
elements in the fallback content. (Focus has no effect on mouse interaction events.)
[DOMEVENTS]
The canvas element has two attributes to control the size of the coordinate space:
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.
The intrinsic dimensions of the canvas element when it represents
embedded content are equal to the dimensions of the element's bitmap.
A canvas element can be sized arbitrarily by a style sheet, its
bitmap is then subject to the 'object-fit' CSS property. [CSSIMAGES]
The bitmaps used with canvas elements can have arbitrary pixel
densities. Typically, the density will match that of the user's screen.
-
context = canvas .
getContext(contextId [, ... ]) -
Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API, either "
2d" or "webgl". Subsequent arguments are handled by that API.This specification defines the "
2d" context below. There is also a specification that defines a "webgl" context. [WEBGL]Returns null if the given context ID is not supported, if the canvas has already been initialized with the other context type (e.g. trying to get a "
2d" context after getting a "webgl" context).Throws an
InvalidStateErrorif thesetContext()ortransferControlToProxy()methods have been used. -
supported = canvas .
supportsContext(contextId [, ... ]) -
Returns false if calling
getContext()with the same arguments would definitely return null, and true otherwise.This return value is not a guarantee that
getContext()will or will not return an object, as conditions (e.g. availability of system resources) can vary over time.Throws an
InvalidStateErrorif thesetContext()ortransferControlToProxy()methods have been used. -
canvas .
setContext(context) -
Sets the
canvas' rendering context to the given object.Throws an
InvalidStateErrorexception if thegetContext()ortransferControlToProxy()methods have been used.
-
url = canvas .
toDataURL( [ type, ... ] ) -
url = canvas .
toDataURLHD( [ type, ... ] ) -
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 other arguments are specific to the type, and control the way that the image is generated, as given in the table below.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:,".)The
toDataURL()method returns the data at a resolution of 96dpi. ThetoDataURLHD()method returns it at the native canvas bitmap resolution. -
canvas .
toBlob(callback [, type, ... ]) -
canvas .
toBlobHD(callback [, type, ... ]) -
Creates a
Blobobject 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 other arguments are specific to the type, and control the way that the image is generated, as given in the table below.The
toBlob()method provides the data at a resolution of 96dpi. ThetoBlobHD()method provides it at the native canvas bitmap resolution.
4.8.11.1 Proxying canvases to workers
Since DOM nodes cannot be accessed across worker boundaries, a proxy object is needed to enable
workers to render to canvas elements in Documents.
interface CanvasProxy {
void setContext(RenderingContext context);
};
CanvasProxy implements Transferable;
-
canvasProxy = canvas .
transferControlToProxy() -
Returns a
CanvasProxyobject that can be used to transfer control for this canvas over to another document (e.g. aniframefrom another origin) or to a worker.Throws an
InvalidStateErrorexception if thegetContext()orsetContext()methods have been used. -
canvasProxy .
setContext(context) -
Sets the
CanvasProxyobject'scanvaselement's rendering context to the given object.Throws an
InvalidStateErrorexception if theCanvasProxyhas been transfered.
The transferControlToProxy()
method of the canvas element, when invoked, must run following the steps:
If the
canvaselement's canvas context mode is not none, throw anInvalidStateErrorand abort these steps.Set the
canvaselement's context mode to proxied.Return a
CanvasProxyobject bound to thiscanvaselement.
A CanvasProxy object can be neutered (like any Transferable object),
meaning it can no longer be transferred, and
can be disabled, meaning it can no longer be bound
to rendering contexts. When first created, a CanvasProxy object must be neither.
A CanvasProxy is created with a link to a canvas element. A
CanvasProxy object that has not been disabled must have a strong reference to its canvas
element.
The setContext(context) method of CanvasProxy objects, when invoked,
must run following the steps:
If the
CanvasProxyobject has been disabled, throw anInvalidStateErrorand abort these steps.If the
CanvasProxyobject has not been neutered, then neuter it.If context's context bitmap mode is fixed, then throw an
InvalidStateErrorand abort these steps.If context's context bitmap mode is bound, then run context's unbinding steps and set its context's context bitmap mode to unbound.
Run context's binding steps to bind it to this
CanvasProxyobject'scanvaselement.Set the context's context bitmap mode to bound.
To transfer a
CanvasProxy object old to a new owner owner,
a user agent must create a new CanvasProxy object linked to the same
canvas element as old, thus obtaining new,
must neuter and disable the old object, and must
finally return new.
Here is a clock implemented on a worker. First, the main page:
<!DOCTYPE HTML>
<title>Clock</title>
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName('canvas')[0];
var proxy = canvas.transferControlToProxy());
var worker = new Worker('clock.js');
worker.postMessage(proxy, [proxy]);
</script>
Second, the worker:
onmessage = function (event) {
var context = new CanvasRenderingContext2d();
event.data.setContext(context); // event.data is the CanvasProxy object
setInterval(function () {
context.clearRect(0, 0, context.width, context.height);
context.fillText(0, 100, new Date());
context.commit();
}, 1000);
};
4.8.11.2 The 2D rendering context
typedef (HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or CanvasRenderingContext2D or ImageBitmap) CanvasImageSource; [Constructor(optional unsigned long width, unsigned long height)] interface CanvasRenderingContext2D { // back-reference to the canvas readonly attribute HTMLCanvasElement canvas; // canvas dimensions attribute unsigned long width; attribute unsigned long height; // for contexts that aren't directly fixed to a specific canvas void commit(); // push the image to the output bitmap // state void save(); // push state on state stack void restore(); // pop state stack and restore state // transformations (default transform is the identity matrix) attribute SVGMatrix currentTransform; void scale(unrestricted double x, unrestricted double y); void rotate(unrestricted double angle); void translate(unrestricted double x, unrestricted double y); void transform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f); void setTransform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f); void resetTransform(); // compositing attribute unrestricted double globalAlpha; // (default 1.0) attribute DOMString globalCompositeOperation; // (default source-over) // image smoothing attribute boolean imageSmoothingEnabled; // (default true) // colors and styles (see also the CanvasDrawingStyles interface) attribute (DOMString or CanvasGradient or CanvasPattern) strokeStyle; // (default black) attribute (DOMString or CanvasGradient or CanvasPattern) fillStyle; // (default black) CanvasGradient createLinearGradient(double x0, double y0, double x1, double y1); CanvasGradient createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1); CanvasPattern createPattern(CanvasImageSource image, DOMString repetition); // shadows attribute unrestricted double shadowOffsetX; // (default 0) attribute unrestricted double shadowOffsetY; // (default 0) attribute unrestricted double shadowBlur; // (default 0) attribute DOMString shadowColor; // (default transparent black) // rects void clearRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h); void fillRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h); void strokeRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h); // path API (see also CanvasPathMethods) void beginPath(); void fill(); void fill(Path path); void stroke(); void stroke(Path path); void drawSystemFocusRing(Element element); void drawSystemFocusRing(Path path, Element element); boolean drawCustomFocusRing(Element element); boolean drawCustomFocusRing(Path path, Element element); void scrollPathIntoView(); void scrollPathIntoView(Path path); void clip(); void clip(Path path); void resetClip(); boolean isPointInPath(unrestricted double x, unrestricted double y); boolean isPointInPath(Path path, unrestricted double x, unrestricted double y); // text (see also the CanvasDrawingStyles interface) void fillText(DOMString text, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth); void strokeText(DOMString text, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth); TextMetrics measureText(DOMString text); // drawing images void drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy); void drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh); void drawImage(CanvasImageSource image, unrestricted double sx, unrestricted double sy, unrestricted double sw, unrestricted double sh, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh); // hit regions void addHitRegion(HitRegionOptions options); void removeHitRegion(HitRegionOptions options); // pixel manipulation ImageData createImageData(double sw, double sh); ImageData createImageData(ImageData imagedata); ImageData createImageDataHD(double sw, double sh); ImageData getImageData(double sx, double sy, double sw, double sh); ImageData getImageDataHD(double sx, double sy, double sw, double sh); void putImageData(ImageData imagedata, double dx, double dy); void putImageData(ImageData imagedata, double dx, double dy, double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight); void putImageDataHD(ImageData imagedata, double dx, double dy); void putImageDataHD(ImageData imagedata, double dx, double dy, double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight); }; CanvasRenderingContext2D implements CanvasDrawingStyles; CanvasRenderingContext2D implements CanvasPathMethods; [NoInterfaceObject] interface CanvasDrawingStyles { // line caps/joins attribute unrestricted double lineWidth; // (default 1) attribute DOMString lineCap; // "butt", "round", "square" (default "butt") attribute DOMString lineJoin; // "round", "bevel", "miter" (default "miter") attribute unrestricted double miterLimit; // (default 10) // dashed lines void setLineDash(sequence<unrestricted double> segments); // default empty sequence<unrestricted double> getLineDash(); attribute unrestricted double lineDashOffset; // text attribute DOMString font; // (default 10px sans-serif) attribute DOMString textAlign; // "start", "end", "left", "right", "center" (default: "start") attribute DOMString textBaseline; // "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" (default: "alphabetic") attribute DOMString direction; // "ltr", "rtl", "inherit" (default: "inherit") }; [NoInterfaceObject] interface CanvasPathMethods { // shared path API methods void closePath(); void moveTo(unrestricted double x, unrestricted double y); void lineTo(unrestricted double x, unrestricted double y); void quadraticCurveTo(unrestricted double cpx, unrestricted double cpy, unrestricted double x, unrestricted double y); void bezierCurveTo(unrestricted double cp1x, unrestricted double cp1y, unrestricted double cp2x, unrestricted double cp2y, unrestricted double x, unrestricted double y); void arcTo(unrestricted double x1, unrestricted double y1, unrestricted double x2, unrestricted double y2, unrestricted double radius); void arcTo(unrestricted double x1, unrestricted double y1, unrestricted double x2, unrestricted double y2, unrestricted double radiusX, unrestricted double radiusY, unrestricted double rotation); void rect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h); void arc(unrestricted double x, unrestricted double y, unrestricted double radius, unrestricted double startAngle, unrestricted double endAngle, optional boolean anticlockwise = false); void ellipse(unrestricted double x, unrestricted double y, unrestricted double radiusX, unrestricted double radiusY, unrestricted double rotation, unrestricted double startAngle, unrestricted double endAngle, boolean anticlockwise); }; interface CanvasGradient { // opaque object void addColorStop(double offset, DOMString color); }; interface CanvasPattern { // opaque object void setTransform(SVGMatrix transform); }; interface TextMetrics { // x-direction readonly attribute double width; // advance width readonly attribute double actualBoundingBoxLeft; readonly attribute double actualBoundingBoxRight; // y-direction readonly attribute double fontBoundingBoxAscent; readonly attribute double fontBoundingBoxDescent; readonly attribute double actualBoundingBoxAscent; readonly attribute double actualBoundingBoxDescent; readonly attribute double emHeightAscent; readonly attribute double emHeightDescent; readonly attribute double hangingBaseline; readonly attribute double alphabeticBaseline; readonly attribute double ideographicBaseline; }; dictionary HitRegionOptions { Path? path = null; DOMString id = ""; DOMString? parentID = null; DOMString cursor = "inherit"; // for control-backed regions: Element? control = null; // for unbacked regions: DOMString? label = null; DOMString? role = null; }; interface ImageData { readonly attribute unsigned long width; readonly attribute unsigned long height; readonly attribute Uint8ClampedArray data; }; [Constructor(optional Element scope)] interface DrawingStyle { }; DrawingStyle implements CanvasDrawingStyles; [Constructor, Constructor(Path path), Constructor(DOMString d)] interface Path { void addPath(Path path, SVGMatrix? transformation); void addPathByStrokingPath(Path path, CanvasDrawingStyles styles, SVGMatrix? transformation); void addText(DOMString text, CanvasDrawingStyles styles, SVGMatrix? transformation, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth); void addPathByStrokingText(DOMString text, CanvasDrawingStyles styles, SVGMatrix? transformation, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth); void addText(DOMString text, CanvasDrawingStyles styles, SVGMatrix? transformation, Path path, optional unrestricted double maxWidth); void addPathByStrokingText(DOMString text, CanvasDrawingStyles styles, SVGMatrix? transformation, Path path, optional unrestricted double maxWidth); }; Path implements CanvasPathMethods;
-
context = canvas .
getContext('2d') -
Returns a
CanvasRenderingContext2Dobject that is permanently bound to a particularcanvaselement. -
context = new
CanvasRenderingContext2D( [ width, height ] ) -
Returns an unbound
CanvasRenderingContext2Dobject with an implied bitmap with the given dimensions in CSS pixels (300x150, if the arguments are omitted). -
context .
canvas -
Returns the
canvaselement, if the rendering context was obtained using thegetContext()method. -
context .
width -
context .
height -
Return the dimensions of the bitmap, in CSS pixels.
Can be set, to update the bitmap's dimensions. If the rendering context is bound to a canvas, this will also update the canvas' intrinsic dimensions.
-
context .
commit() -
If the rendering context is bound to a
canvas, display the current frame.
4.8.11.2.1 Implementation notes
Although the way the specification is written it might sound like an implementation needs to
track up to four bitmaps per canvas or rendering context — one scratch bitmap,
one output bitmap for the rendering context, one bitmap for the canvas,
and one bitmap for the actually currently rendered image — user agents can in fact generally
optimise this to only one or two.
The scratch bitmap, when it isn't the same bitmap as the output
bitmap, is only directly observable if it is read, and therefore 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 commit(), drawImage(), or the ImageBitmap()
constructor). 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 the rendering commands from the scratch bitmap can be applied without the rendering being updated midway.
4.8.11.2.2 The canvas state
Each CanvasRenderingContext2D rendering context maintains a stack of drawing
states. Drawing states consist of:
- The current transformation matrix.
- The current clipping region.
- The current values of the following attributes:
strokeStyle,fillStyle,globalAlpha,lineWidth,lineCap,lineJoin,miterLimit,lineDashOffset,shadowOffsetX,shadowOffsetY,shadowBlur,shadowColor,globalCompositeOperation,font,textAlign,textBaseline,direction,imageSmoothingEnabled. - The current dash list.
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() -
Pushes the current state onto the stack.
-
context .
restore() -
Pops the top state on the stack, restoring the context to that state.
4.8.11.2.3
DrawingStyle objects
All the line styles (line width, caps, joins, and dash patterns)
and text styles (fonts) described in the next two sections apply to
CanvasRenderingContext2D objects and to
DrawingStyle objects. This section defines the
constructor used to obtain a DrawingStyle object. This
object is then used by methods on Path objects to
control how text and paths are rasterised and stroked.
-
styles = new
DrawingStyle( [ element ] ) -
Creates a new
DrawingStyleobject, optionally using a specific element for resolving relative keywords and sizes in font specifications.
4.8.11.2.4 Line styles
-
context .
lineWidth[ = value ] -
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 ] -
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, andsquare. Other values are ignored. -
context .
lineJoin[ = value ] -
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, andmiter. Other values are ignored. -
context .
miterLimit[ = value ] -
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) -
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() -
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 -
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.8.11.2.5 Text styles
-
context .
font[ = value ] -
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
canvaselement. -
context .
textAlign[ = value ] -
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 ] -
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 ] -
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 textBaseline 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 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 baseline
-
bottom - The bottom of the em square
The textBaseline 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
canvaselement orDocumentas appropriate.
The text preparation algorithm is as follows. It takes as input a string text, a CanvasDrawingStyles 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.)
If maxWidth was provided but is less than or equal to zero, return an empty array.
Replace all the space characters in text with U+0020 SPACE characters.
Let font be the current font of target, as given by that object's
fontattribute.-
Apply the appropriate step from the following list to determine the value of direction:
- If the target object's
directionattribute has the value "ltr" - Let direction be 'ltr'.
- If the target object's
directionattribute 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
Documentand thatDocumenthas a root element child - Let direction be the directionality of the target object's font style source object's root element child.
- Otherwise
- Let direction be 'ltr'.
- If the target object's
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]
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.
-
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
textAlignandtextBaselinevalues as follows:Horizontal position:
- If
textAlignisleft - If
textAlignisstartand direction is 'ltr' - If
textAlignisendand 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
textAlignisright - If
textAlignisendand direction is 'ltr' - If
textAlignisstartand 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
textAligniscenter - 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
textBaselineistop - Let the anchor point's vertical position be the top of the em box of the first available font of the inline box.
- If
textBaselineishanging - Let the anchor point's vertical position be the hanging baseline of the first available font of the inline box.
- If
textBaselineismiddle - 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
textBaselineisalphabetic - Let the anchor point's vertical position be the alphabetic baseline of the first available font of the inline box.
- If
textBaselineisideographic - Let the anchor point's vertical position be the ideographic baseline of the first available font of the inline box.
- If
textBaselineisbottom - Let the anchor point's vertical position be the bottom of the em box of the first available font of the inline box.
- If
-
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.
Return result, physical alignment, and the inline box.
4.8.11.2.6 Building paths
Each object implementing the CanvasPathMethods
interface has 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 lines, 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 fewer than two points are ignored when
painting the path.
When an object implementing the CanvasPathMethods
interface is created, its path
must be initialized to zero subpaths.
-
context .
moveTo(x, y) -
path .
moveTo(x, y) -
Creates a new subpath with the given point.
-
context .
closePath() -
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) -
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) -
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) -
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, radiusX [, radiusY, rotation ]) -
path .
arcTo(x1, y1, x2, y2, radiusX [, radiusY, rotation ]) -
Adds an arc with the given control points and radius to the current subpath, connected to the previous point by a straight line.
If two radii are provided, the first controls the width of the arc's ellipse, and the second controls the height. If only one is provided, or if they are the same, the arc is from a circle. In the case of an ellipse, the rotation argument controls the clockwise inclination of the ellipse relative to the x-axis.
Throws an
IndexSizeErrorexception if the given radius is negative.


-
context .
arc(x, y, radius, startAngle, endAngle [, anticlockwise ] ) -
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
IndexSizeErrorexception if the given radius is negative.
-
context .
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) -
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
IndexSizeErrorexception if the given radius is negative. -
context .
rect(x, y, w, h) -
path .
rect(x, y, w, h) -
Adds a new closed subpath to the path, representing the given rectangle.
4.8.11.2.7
Path objects
Path objects can be used to declare paths that are
then later used on CanvasRenderingContext2D objects. In
addition to many of the APIs described in earlier sections,
Path objects have methods to combine paths, and to add
text to paths.
-
path = new
Path() -
Creates a new empty
Pathobject. -
path = new
Path(path) -
Creates a new
Pathobject that is a copy of the argument. -
path = new
Path(d) -
Creates a new path with the path described by the argument, interpreted as SVG path data. [SVG]
-
path .
addPath(path, transform) -
path .
addPathByStrokingPath(path, styles, transform) -
Adds to the path the path given by the argument.
In the case of the stroking variants, the line styles are taken from the styles argument, which can be either a
DrawingStyleobject or aCanvasRenderingContext2Dobject. -
path .
addText(text, styles, transform, x, y [, maxWidth ]) -
path .
addText(text, styles, transform, path [, maxWidth ]) -
path .
addPathByStrokingText(text, styles, transform, x, y [, maxWidth ]) -
path .
addPathByStrokingText(text, styles, transform, path [, maxWidth ]) -
Adds to the path a series of subpaths corresponding to the given text. If the arguments give a coordinate, the text is drawn horizontally at the given coordinates. If the arguments give a path, the text is drawn along the path. If a maximum width is provided, the text will be scaled to fit that width if necessary.
The font, and in the case of the stroking variants, the line styles, are taken from the styles argument, which can be either a
DrawingStyleobject or aCanvasRenderingContext2Dobject.
4.8.11.2.8 Transformations
Each CanvasRenderingContext2D object has a
current transformation matrix, as well as methods (described
in this section) to manipulate it. When a
CanvasRenderingContext2D object is created, its
transformation matrix must be initialized to the identity
transform.
The transformation matrix is applied to coordinates when creating
the current default path, and when painting text,
shapes, and Path objects, on
CanvasRenderingContext2D objects.
Most of the API uses SVGMatrix objects
rather than this API. This API remains mostly for historical
reasons.
-
context .
currentTransform[ = value ] -
Returns the transformation matrix, as an
SVGMatrixobject.Can be set, to change the transformation matrix.
-
context .
scale(x, y) -
Changes the transformation matrix to apply a scaling transformation with the given characteristics.
-
context .
rotate(angle) -
Changes the transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.
-
context .
translate(x, y) -
Changes the transformation matrix to apply a translation transformation with the given characteristics.
-
context .
transform(a, b, c, d, e, f) -
Changes the transformation matrix to apply the matrix given by the arguments as described below.
-
context .
setTransform(a, b, c, d, e, f) -
Changes the transformation matrix to the matrix given by the arguments as described below.
-
context .
resetTransform() -
Changes the transformation matrix to the identity transform.
| a | c | e |
| b | d | f |
| 0 | 0 | 1 |
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 should 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.
4.8.11.2.9 Image sources for 2D rendering contexts
Several methods in the CanvasRenderingContext2D API 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:
-
HTMLImageElement(imgelements) -
HTMLVideoElement(videoelements) -
HTMLCanvasElement(canvaselements) CanvasRenderingContext2DBitmapImage
When a user agent is required to check the usability of the image
argument, where image is a CanvasImageSource object, the
user agent must run these steps, which return either good, bad, or
aborted:
If the image argument is an
HTMLImageElementobject that is not fully decodable, or if the image argument is anHTMLVideoElementobject whosereadyStateattribute is eitherHAVE_NOTHINGorHAVE_METADATA, then return bad and abort these steps.-
If the image argument is an
HTMLCanvasElementobject with either a horizontal dimension or a vertical dimension equal to zero, then the implementation throw anInvalidStateErrorexception and return aborted.
When a CanvasImageSource object represents an HTMLImageElement, the
element's image must be used as the source image.
Specifically, when a CanvasImageSource object represents an animated image in an
HTMLImageElement, the user agent must use the poster frame of the animation, or, if
there is no poster frame, 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 a CanvasRenderingContext2D, the
object's scratch 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 a BitmapImage, the
object's bitmap image data must be used as the source image.
The image argument is not origin-clean if it is an
HTMLImageElement or HTMLVideoElement whose origin is not
the same as the entry script's origin,
or if it is an HTMLCanvasElement whose bitmap's origin-clean flag is false, or if it is a
CanvasRenderingContext2D object whose scratch bitmap's origin-clean flag is false.
4.8.11.2.10 Fill and stroke styles
-
context .
fillStyle[ = value ] -
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
CanvasGradientorCanvasPatternobject. Invalid values are ignored. -
context .
strokeStyle[ = value ] -
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
CanvasGradientorCanvasPatternobject. 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) -
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
IndexSizeErrorexception if the offset is out of range. Throws aSyntaxErrorexception if the color cannot be parsed. -
gradient = context .
createLinearGradient(x0, y0, x1, y1) -
Returns a
CanvasGradientobject 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) -
Returns a
CanvasGradientobject 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
IndexSizeErrorexception.
Patterns are represented by objects implementing the opaque
CanvasPattern interface.
-
pattern = context .
createPattern(image, repetition) -
Returns a
CanvasPatternobject 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), andno-repeat(neither). If the repetition argument is empty, the valuerepeatis used.If the image has no image data, throws an
InvalidStateErrorexception. If the second argument isn't one of the allowed values, throws aSyntaxErrorexception. If the image isn't yet fully decoded, then the method returns null. -
pattern .
setTransform(transform) -
Sets the transformation matrix that will be used when rendering the pattern during a fill or stroke painting operation.
4.8.11.2.11 Drawing rectangles to the bitmap
There are three methods that immediately draw rectangles to the bitmap. They 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) -
Clears all pixels on the bitmap in the given rectangle to transparent black.
-
context .
fillRect(x, y, w, h) -
Paints the given rectangle onto the bitmap, using the current fill style.
-
context .
strokeRect(x, y, w, h) -
Paints the box that outlines the given rectangle onto the bitmap, using the current stroke style.
4.8.11.2.12 Drawing text to the bitmap
-
context .
fillText(text, x, y [, maxWidth ] ) -
context .
strokeText(text, x, y [, maxWidth ] ) -
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) -
Returns a
TextMetricsobject with the metrics of the given text in the current font. -
metrics .
width -
metrics .
actualBoundingBoxLeft -
metrics .
actualBoundingBoxRight -
metrics .
fontBoundingBoxAscent -
metrics .
fontBoundingBoxDescent -
metrics .
actualBoundingBoxAscent -
metrics .
actualBoundingBoxDescent -
metrics .
emHeightAscent -
metrics .
emHeightDescent -
metrics .
hangingBaseline -
metrics .
alphabeticBaseline -
metrics .
ideographicBaseline -
Returns the measurement described below.
-
widthattribute The width of that inline box, in CSS pixels. (The text's advance width.)
-
actualBoundingBoxLeftattribute -
The distance parallel to the baseline from the alignment point given by the
textAlignattribute 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. -
actualBoundingBoxRightattribute -
The distance parallel to the baseline from the alignment point given by the
textAlignattribute 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. -
fontBoundingBoxAscentattribute -
The distance from the horizontal line indicated by the
textBaselineattribute to the top of the highest bounding rectangle of all the fonts used to render the text, 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 must have a consistent height even if the exact text being rendered changes. The
actualBoundingBoxAscentattribute (and its corresponding attribute for the descent) are useful when drawing a bounding box around specific text. -
fontBoundingBoxDescentattribute The distance from the horizontal line indicated by the
textBaselineattribute to the bottom of the lowest bounding rectangle of all the fonts used to render the text, in CSS pixels; positive numbers indicating a distance going down from the given baseline.-
actualBoundingBoxAscentattribute -
The distance from the horizontal line indicated by the
textBaselineattribute 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
actualBoundingBoxAscentof 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 (textBaselinevalue "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. -
actualBoundingBoxDescentattribute The distance from the horizontal line indicated by the
textBaselineattribute 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.-
emHeightAscentattribute The distance from the horizontal line indicated by the
textBaselineattribute to the top of the em square in the line box, in CSS pixels; positive numbers indicating that the given baseline is below the top of the em square (so this value will usually be positive). Zero if the given baseline is the top of the em square; half the font size if the given baseline is the middle of the em square.-
emHeightDescentattribute The distance from the horizontal line indicated by the
textBaselineattribute to the bottom of the em square in the line box, in CSS pixels; positive numbers indicating that the given baseline is below the bottom of the em square (so this value will usually be negative). (Zero if the given baseline is the top of the em square.)-
hangingBaselineattribute The distance from the horizontal line indicated by the
textBaselineattribute to the hanging baseline of the line 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.)-
alphabeticBaselineattribute The distance from the horizontal line indicated by the
textBaselineattribute to the alphabetic baseline of the line 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.)-
ideographicBaselineattribute The distance from the horizontal line indicated by the
textBaselineattribute to the ideographic baseline of the line box, in CSS pixels; positive numbers indicating that the given baseline is below the ideographic baseline. (Zero if the given baseline is the ideographic 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 may 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.8.11.2.13 Drawing paths to the canvas
The context always has 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() -
Resets the current default path.
-
context .
fill() -
context .
fill(path) -
Fills the subpaths of the current default path or the given path with the current fill style.
-
context .
stroke() -
context .
stroke(path) -
Strokes the subpaths of the current default path or the given path with the current stroke style.
-
context .
drawSystemFocusRing(element) -
context .
drawSystemFocusRing(path, element) -
If the given element is focused, draws a focus ring around the current default path or hte given path, following the platform conventions for focus rings.
-
shouldDraw = context .
drawCustomFocusRing(element) -
shouldDraw = context .
drawCustomFocusRing(path, element) -
If the given element is focused, and the user has configured his system to draw focus rings in a particular manner (for example, high contrast focus rings), draws a focus ring around the current default path or the given path and returns false.
Otherwise, returns true if the given element is focused, and false otherwise. This can thus be used to determine when to draw a focus ring (see the example below).
-
context .
scrollPathIntoView() -
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.
-
context .
clip() -
context .
clip(path) -
Further constrains the clipping region to the current default path or the given path.
-
context .
resetClip() -
Unconstrains the clipping region.
-
context .
isPointInPath(x, y) -
context .
isPointInPath(path, x, y) -
Returns true if the given point is in the current default path or the given path.
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);
if (paint && context.drawCustomFocusRing(element)) {
context.strokeStyle = 'silver';
context.stroke();
}
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.8.11.2.14 Drawing images
To draw images, the drawImage method
can be used.
-
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:

If the first argument isn't an
img,canvas, orvideoelement, throws aTypeMismatchErrorexception. If the image has no image data, throws anInvalidStateErrorexception. If the one of the source rectangle dimensions is zero, throws anIndexSizeErrorexception. If the image isn't yet fully decoded, then nothing is drawn.
4.8.11.2.15 Hit regions
A hit region list is a list of hit regions for a bitmap.
Each hit region consists of the following information:
A set of pixels on the bitmap for which this region is responsible.
A bounding circumference on the bitmap that surrounds the hit region's set of pixels as they stood when it was created.
Optionally, a non-empty string representing an ID for distinguishing the region from others.
Optionally, a reference to another region that acts as the parent for this one.
A count of regions that have this one as their parent, known as the hit region's child count.
A cursor specification, in the form of either a CSS cursor value, or the string "
inherit" meaning that the cursor of the hit region's parent, if any, or of thecanvaselement, if not, is to be used instead.-
Optionally, either a control, or an unbacked region description.
A control is just a reference to an
Elementnode, to which, in certain conditions, the user agent will route events, and from which the user agent will determine the state of the hit region for the purposes of accessibility tools. (The control is ignored when it is not a descendant of thecanvaselement.)An unbacked region description consists of the following:
-
Optionally, a label.
An ARIA role, which, if the unbacked region description also has a label, could be the empty string.
-
-
context .
addHitRegion(options) -
Adds a hit region to the bitmap. The argument is an object with the following members:
-
path(default null) - A
Pathobject that describes the pixels that form part of the region. If this member is not provided or is set to null, the current default path is used instead. -
id(default empty string) - The ID to use for this region. This is used in
MouseEventevents on thecanvas(event.region) and as a way to reference this region in later calls toaddHitRegion(). -
parentID(default null) - The ID of the parent region, for purposes of navigation by accessibility tools and for cursor fallback.
-
cursor(default "inherit") - The cursor to use when the mouse is over this region. The
value "
inherit" means to use the cursor for the parent region (as specified by theparentIDmember), if any, or to use thecanvaselement's cursor if the region has no parent. -
control(default null) - An element (that is a descendant of the
canvas) to which events are to be routed, and which accessibility tools are to use as a surrogate for describing and interacting with this region. -
label(default null) - A text label for accessibility tools to use as a description of this region, if there is no control.
-
role(default null) - An ARIA role for accessibility tools to use to determine how to represent this region, if there is no control.
Hit regions can be used for a variety of purposes:
- With an ID, they can make hit detection easier by having the user agent check which region the mouse is over and include the ID in the mouse events.
- With a control, they can make routing events to DOM elements
automatic, allowing e.g. clicks on a
canvasto automatically submit a form via abuttonelement. - With a label, they can make it easier for users to explore a
canvaswithout seeing it, e.g. by touch on a mobile device. - With a cursor, they can make it easier for different regions
of the
canvasto have different cursors, with the user agent automatically switching between them.
-
-
context .
removeHitRegion(options) -
Removes a hit region (and all its ancestors) from the canvas bitmap. The argument is the ID of a region added using
addHitRegion().The pixels that were covered by this region and its descendants are effectively cleared by this operation, leaving the regions non-interactive. In particular, regions that occupied the same pixels before the removed regions were added, overlapping them, do not resume their previous role.
The MouseEvent interface is extended to support hit
regions:
partial interface MouseEvent { readonly attribute DOMString? region; }; partial dictionary MouseEventInit { DOMString? region; };
-
event .
region -
If the mouse was over a hit region, then this returns the hit region's ID, if it has one.
Otherwise, returns null.
4.8.11.2.16 Pixel manipulation
-
imagedata = context .
createImageData(sw, sh) -
Returns an
ImageDataobject with the given dimensions. All the pixels in the returned object are transparent black. -
imagedata = context .
createImageData(imagedata) -
Returns an
ImageDataobject with the same dimensions as the argument. All the pixels in the returned object are transparent black. -
imagedata = context .
createImageDataHD(sw, sh) -
Returns an
ImageDataobject whose dimensions equal the dimensions given in the arguments, multiplied by the number of pixels in the canvas bitmap that correspond to each coordinate space unit. All the pixels in the returned object are transparent black. -
imagedata = context .
getImageData(sx, sy, sw, sh) -
Returns an
ImageDataobject containing the image data for the given rectangle of the bitmap.Throws an
IndexSizeErrorexception if the either of the width or height arguments are zero.The data will be returned with one pixel of image data for each coordinate space unit on the canvas (ignoring transforms).
-
imagedata = context .
getImageDataHD(sx, sy, sw, sh) -
Returns an
ImageDataobject containing the image data for the given rectangle of the bitmap.Throws an
IndexSizeErrorexception if the either of the width or height arguments are zero.The data will be returned at the same resolution as the canvas bitmap.
-
imagedata .
width -
imagedata .
height -
Returns the actual dimensions of the data in the
ImageDataobject, in pixels. For objects returned by the non-HD variants of the methods in this API, this will correspond to the dimensions given to the methods. For the HD variants, the number of pixels might be different than the number of corresponding coordinate space units. -
imagedata .
data -
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 ]) -
Paints the data from the given
ImageDataobject onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.The
globalAlphaandglobalCompositeOperationattributes, 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 a
NotSupportedErrorexception if any of the arguments are not finite.Each pixel in the image data is mapped to one coordinate space unit on the bitmap.
-
context .
putImageDataHD(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ]) -
Paints the data from the given
ImageDataobject onto the bitmap, at the bitmap's native pixel density. If a dirty rectangle is provided, only the pixels from that rectangle are painted.The
globalAlphaandglobalCompositeOperationattributes, 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 a
NotSupportedErrorexception if any of the arguments are not finite.
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.createImageDataHD(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.putImageDataHD(data, 0, 0);
// support methods
function FillPlasma(data, color) { ... }
function AddCloud(data, x, y) { ... }
Here is an example of using getImageDataHD() and
putImageDataHD()
to implement an edge detection filter.
<!DOCTYPE HTML>
<html>
<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.getImageDataHD(0, 0, canvas.width, canvas.height);
// get an empty slate to put the data into
var output = context.createImageDataHD(canvas.width, canvas.height);
// alias some variables for convenience
// notice that we are using input.width and input.height here
// as they might not be the same as canvas.width and canvas.height
// (in particular, they might be different on high-res displays)
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.putImageDataHD(output, 0, 0);
}
</script>
</head>
<body onload="init()">
<canvas></canvas>
</body>
</html>
4.8.11.2.17 Compositing
-
context .
globalAlpha[ = value ] -
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 ] -
Returns the current composition operation, from the list below.
Can be set, to change the composition operation. Unknown values are ignored.
source-atop- A atop B. Display the source image wherever both images are opaque. Display the destination image wherever the destination image is opaque but the source image is transparent. Display transparency elsewhere.
source-in- A in B. Display the source image wherever both the source image and destination image are opaque. Display transparency elsewhere.
source-out- A out B. Display the source image wherever the source image is opaque and the destination image is transparent. Display transparency elsewhere.
-
source-over(default) - A over B. Display the source image wherever the source image is opaque. Display the destination image elsewhere.
destination-atop-
B atop A. Same as
source-atopbut using the destination image instead of the source image and vice versa. destination-in-
B in A. Same as
source-inbut using the destination image instead of the source image and vice versa. destination-out-
B out A. Same as
source-outbut using the destination image instead of the source image and vice versa. destination-over-
B over A. Same as
source-overbut using the destination image instead of the source image and vice versa. lighter- A plus B. Display the sum of the source image and destination image, with color values approaching 255 (100%) as a limit.
copy- A (B is ignored). Display the source image instead of the destination image.
xor- A xor B. Exclusive OR of the source image and destination image.
4.8.11.2.18 Image smoothing
-
context .
imageSmoothingEnabled[ = value ] -
Returns whether pattern fills and the
drawImage()method will attempt to smooth images if they have to rescale them (as opposed to just rendering the images with "big pixels").Can be set, to change whether images are smoothed (true) or not (false).
4.8.11.2.19 Shadows
All drawing operations are affected by the four global shadow attributes.
-
context .
shadowColor[ = value ] -
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 ] -
context .
shadowOffsetY[ = value ] -
Returns the current shadow offset.
Can be set, to change the shadow offset. Values that are not finite numbers are ignored.
-
context .
shadowBlur[ = value ] -
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, shadows effectively won't render
(since the shape will overwrite the shadow).
4.8.11.2.20 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.
To indicate which focusable part of the canvas is currently
focused, authors should use the drawSystemFocusRing()
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.
Authors should avoid implementing text editing controls using the
canvas element. Doing so has a large number of
disadvantages:
- Mouse placement of the caret has to be reimplemented.
- Keyboard movement of the caret has to be reimplemented (possibly across lines, for multiline text input).
- Scrolling of the text field has to be implemented (horizontally for long lines, vertically for multiline input).
- Native features such as copy-and-paste have to be reimplemented.
- Native features such as spell-checking have to be reimplemented.
- Native features such as drag-and-drop have to be reimplemented.
- Native features such as page-wide text search have to be reimplemented.
- Native features specific to the user, for example custom text services, have to be reimplemented. This is close to impossible since each user might have different services installed, and there is an unbounded set of possible such services.
- Bidirectional text editing has to be reimplemented.
- For multiline text editing, line wrapping has to be implemented for all relevant languages.
- Text selection has to be reimplemented.
- Dragging of bidirectional text selections has to be reimplemented.
- Platform-native keyboard shortcuts have to be reimplemented.
- Platform-native input method editors (IMEs) have to be reimplemented.
- Undo and redo functionality has to be reimplemented.
- Accessibility features such as magnification following the caret or selection have to be reimplemented.
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.8.11.2.21 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>
4.8.11.3 Pixel density
The user agent may use any square pixel density for the bitmaps of a canvas and
its rendering contexts. Once a canvas has a bitmap, that canvas must keep its
resolution for its lifetime.
In general, user agents are encouraged to use a pixel density equal to the screen pixel density. Ideally, the number of device pixels per CSS pixel would be a multiple of two. Several factors can affect the screen pixel density: most prominently the actual display pixel density, but also important is the current zoom level.
All the bitmaps created during a single task for
canvas elements and CanvasRenderingContext2D objects must have the same
pixel density.
partial interface Screen { readonly attribute double canvasResolution; };
-
window .
screen.canvasResolution -
Returns the pixel density that has been, or will be, used for bitmaps during this task.
4.8.11.4 Serializing bitmaps to a file
| Type | Other arguments | Reference |
|---|---|---|
image/jpeg
|
The second argument is a number in the range 0.0 to 1.0 inclusive treated as the desired quality level. |