© Copyright 2004-2008 Apple Computer, Inc., Mozilla Foundation, and Opera Software ASA.
You are granted a license to use, reproduce and create derivative works of this document.
canvas elementwidth
height
interface HTMLCanvasElement # type.name type.exists type.delete type.prototype type.replace type.extend : HTMLElement { attribute unsigned long width; # size.attributes size.attributes.type.get size.attributes.type.set attribute unsigned long height; # size.attributes size.attributes.type.get size.attributes.type.set DOMString toDataURL(); DOMString toDataURL(in DOMString type); DOMObject getContext(in DOMString contextId); };
The canvas element represents a
resolution-dependent bitmap canvas, which can be used for rendering
graphs, game graphics, 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 should also provide content that, when presented to the user, conveys
essentially the same function or purpose as the bitmap canvas. 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 # fallback.basic fallback.multiple fallback.nested .
In interactive visual media, if the canvas element is with
script, the canvas element
represents an embedded element with a dynamically created image.
In non-interactive, static, visual media, if the canvas element has been previously painted on
(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 current image and size.
Otherwise, the element represents its fallback
content instead.
In non-visual media, and in visual media if the canvas element is without
script, the canvas element
represents its fallback content instead.
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 rules for parsing non-negative integers must be used to
obtain their numeric values # size.attributes.parse.whitespace size.attributes.parse.nonnumber size.attributes.parse.zero size.attributes.parse.negative size.attributes.parse.zerosuffix size.attributes.parse.floatsuffix size.attributes.parse.badsuffix size.attributes.parse.percentsuffix size.attributes.setAttribute.whitespace size.attributes.setAttribute.nonnumber size.attributes.setAttribute.zero size.attributes.setAttribute.negative size.attributes.setAttribute.zerosuffix size.attributes.setAttribute.floatsuffix size.attributes.setAttribute.badsuffix size.attributes.setAttribute.percentsuffix . If an attribute is missing # size.attributes.default size.attributes.removed , or if parsing its
value returns an error # size.attributes.parse.nonnumber size.attributes.parse.negative size.attributes.setAttribute.nonnumber size.attributes.setAttribute.negative , then the default value must be used instead. The
width attribute
defaults to 300, and the height attribute defaults to 150 # size.attributes.default .
The intrinsic dimensions of the canvas element equal the size of the coordinate
space, with the numbers interpreted in CSS pixels. However, the element
can be sized arbitrarily by a style sheet. During rendering, the image is
scaled to fit this layout size # size.attributes.style .
The size of the coordinate space does not necessarily represent the size of the actual bitmap that the user agent will use internally or during rendering. On high-definition displays, for instance, the user agent may internally use a bitmap with two device pixels per unit in the coordinate space, so that the rendering remains at high quality throughout.
Whenever the width and height attributes are set (whether to a new
value or to the previous value), the bitmap and any associated contexts
must be cleared back to their initial state and reinitialized with the
newly specified coordinate space dimensions # initial.reset.different initial.reset.same initial.reset.path initial.reset.clip initial.reset.transform security.reset initial.reset.2dstate .
The width and
height DOM
attributes must reflect the content attributes of
the same name # size.attributes.reflect.1 size.attributes.reflect.2 .
Only one square appears to be drawn in the following example:
// canvas is a reference to a <canvas> element
var context = canvas.getContext('2d');
context.fillRect(0,0,50,50);
canvas.setAttribute('width', '300'); // clears the canvas
context.fillRect(0,100,50,50);
canvas.width = canvas.width; // clears the canvas
context.fillRect(100,0,50,50); // only this square remains
When the canvas is initialized it must be set to fully transparent black # initial.colour .
To draw on the canvas, authors must first obtain a reference to a context using the getContext(contextId) method of the canvas element.
This specification only defines one context, with the name "2d". If getContext()
is called with that exact string for its contextId
argument, then the UA must return a reference to an object implementing
CanvasRenderingContext2D # 2d.getcontext.exists .
Other specifications may define their own contexts, which would return
different objects.
Vendors may also define experimental contexts using the syntax
vendorname-context,
for example, moz-3d.
When the UA is passed an empty string # context.emptystring or a string specifying a context that it does not support # context.unrecognised.badname context.unrecognised.badsuffix context.unrecognised.nullsuffix context.unrecognised.unicode , then it must return null. String comparisons must be literal and case-sensitive # context.casesensitive .
Arguments other than the contextId must be ignored, and must not cause the user agent to raise an exception (as would normally occur if a method was called with the wrong number of arguments) # context.arguments.extra .
A future version of this specification will probably define a
3d context (probably based on the OpenGL ES API).
The toDataURL() method must,
when called with no arguments, return a data: URI
containing a representation of the image as a PNG file # toDataURL.default toDataURL.nocontext toDataURL.primarycolours toDataURL.complexcolours . [PNG].
If the canvas has no pixels (i.e. either its horizontal dimension or its
vertical dimension is zero) then the method must return the string "data:," # toDataURL.zerosize . (This is the shortest data:
URI; it represents the empty string in a text/plain
resource.)
The toDataURL(type) method (when called with one or
more arguments) must return a data: URI
containing a representation of the image in the format given by type. The possible values are MIME types with no
parameters, for example image/png, image/jpeg,
or even maybe image/svg+xml if the implementation actually
keeps enough information to reliably render an SVG image from the canvas.
Only support for image/png is required # toDataURL.png . User agents may
support other types. If the user agent does not support the requested
type, it must return the image using the PNG format # toDataURL.unrecognised .
User agents must convert the provided type to lower case before
establishing if they support that type and before creating the data: URI # toDataURL.lowercase .
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 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:,".)
If the method is invoked with the first argument giving a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.
| Type | Other arguments |
|---|---|
| image/jpeg | The second argument, if it is a number between 0.0 and 1.0, must be treated as the desired quality level. |
Other arguments must be ignored and must not cause the user agent to
raise an exception (as would normally occur if a method was called with
the wrong number of arguments) # toDataURL.arguments.1 toDataURL.arguments.2 toDataURL.arguments.3 . A future version of this specification
will probably allow extra parameters to be passed to toDataURL() to
allow authors to more carefully control compression settings, image
metadata, etc.
When the getContext() method of a canvas element is invoked with 2d as the argument, a CanvasRenderingContext2D
object is returned.
There is only one CanvasRenderingContext2D
object per canvas, so calling the getContext() method with the 2d argument a second time
must return the same object # 2d.getcontext.unique 2d.getcontext.shared .
The 2D context represents a flat Cartesian surface whose origin (0,0) is at the top left corner, with the coordinate space having x values increasing when going right, and y values increasing when going down # 2d.coordinatespace .
interface CanvasRenderingContext2D # 2d.type.exists 2d.type.delete 2d.type.prototype 2d.type.replace 2d.type.extend { // back-reference to the canvas readonly # 2d.canvas.readonly attribute HTMLCanvasElement canvas; // state void save(); // push state on state stack void restore(); // pop state stack and restore state // transformations (default transform is the identity matrix) void scale(in float x, in float y); void rotate(in float angle); void translate(in float x, in float y); void transform(in float m11, in float m12, in float m21, in float m22, in float dx, in float dy); void setTransform(in float m11, in float m12, in float m21, in float m22, in float dx, in float dy); // compositing attribute float globalAlpha; // (default 1.0) attribute DOMString globalCompositeOperation; // (default source-over) // colors and styles attribute DOMObject strokeStyle; // (default black) attribute DOMObject fillStyle; // (default black) CanvasGradient createLinearGradient(in float x0, in float y0, in float x1, in float y1); CanvasGradient createRadialGradient(in float x0, in float y0, in float r0, in float x1, in float y1, in float r1); CanvasPattern createPattern(in HTMLImageElement image, in DOMString repetition); CanvasPattern createPattern(in HTMLCanvasElement image, in DOMString repetition); // line caps/joins attribute float lineWidth; // (default 1) attribute DOMString lineCap; // "butt", "round", "square" (default "butt") attribute DOMString lineJoin; // "round", "bevel", "miter" (default "miter") attribute float miterLimit; // (default 10) // shadows attribute float shadowOffsetX; // (default 0) attribute float shadowOffsetY; // (default 0) attribute float shadowBlur; // (default 0) attribute DOMString shadowColor; // (default transparent black) // rects void clearRect(in float x, in float y, in float w, in float h); void fillRect(in float x, in float y, in float w, in float h); void strokeRect(in float x, in float y, in float w, in float h); // path API void beginPath(); void closePath(); void moveTo(in float x, in float y); void lineTo(in float x, in float y); void quadraticCurveTo(in float cpx, in float cpy, in float x, in float y); void bezierCurveTo(in float cp1x, in float cp1y, in float cp2x, in float cp2y, in float x, in float y); void arcTo(in float x1, in float y1, in float x2, in float y2, in float radius); void rect(in float x, in float y, in float w, in float h); void arc(in float x, in float y, in float radius, in float startAngle, in float endAngle, in boolean anticlockwise); void fill(); void stroke(); void clip(); boolean isPointInPath(in float x, in float y); // 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") void fillText(in DOMString text, in float x, in float y); void fillText(in DOMString text, in float x, in float y, in float maxWidth); void strokeText(in DOMString text, in float x, in float y); void strokeText(in DOMString text, in float x, in float y, in float maxWidth); TextMetrics measureText(in DOMString text); // drawing images void drawImage(in HTMLImageElement image, in float dx, in float dy); void drawImage(in HTMLImageElement image, in float dx, in float dy, in float dw, in float dh); void drawImage(in HTMLImageElement image, in float sx, in float sy, in float sw, in float sh, in float dx, in float dy, in float dw, in float dh); void drawImage(in HTMLCanvasElement image, in float dx, in float dy); void drawImage(in HTMLCanvasElement image, in float dx, in float dy, in float dw, in float dh); void drawImage(in HTMLCanvasElement image, in float sx, in float sy, in float sw, in float sh, in float dx, in float dy, in float dw, in float dh); // pixel manipulation ImageData createImageData(in float sw, in float sh); ImageData getImageData(in float sx, in float sy, in float sw, in float sh); void putImageData(in ImageData imagedata, in float dx, in float dy); void putImageData(in ImageData imagedata, in float dx, in float dy, in float dirtyX, in float dirtyY, in float dirtyWidth, in float dirtyHeight); }; interface CanvasGradient { // opaque object void addColorStop(in float offset, in DOMString color); }; interface CanvasPattern { // opaque object }; interface TextMetrics { readonly attribute float width; }; interface ImageData # 2d.imageData.object.properties 2d.imageData.object.readonly 2d.imageData.object.ctor { readonly attribute long int width; readonly attribute long int height; readonly attribute CanvasPixelArray data; }; interface CanvasPixelArray { readonly attribute unsigned long length; [IndexGetter] float XXX5(in unsigned long index); [IndexSetter] void XXX6(in unsigned long index, in float value); };
The canvas attribute must
return the canvas element that the
context paints on # 2d.canvas.reference .
Unless otherwise stated, for the 2D context interface, any method call with a numeric argument whose value is infinite or a NaN value must be ignored # 2d.transformation.scale.nonfinite 2d.transformation.rotate.nonfinite 2d.transformation.translate.nonfinite 2d.transformation.transform.nonfinite 2d.transformation.setTransform.nonfinite 2d.clearRect.nonfinite 2d.fillRect.nonfinite 2d.strokeRect.nonfinite 2d.path.moveTo.nonfinite 2d.path.lineTo.nonfinite 2d.path.quadraticCurveTo.nonfinite 2d.path.bezierCurveTo.nonfinite 2d.path.arcTo.nonfinite 2d.path.arc.nonfinite 2d.path.rect.nonfinite 2d.drawImage.nonfinite .
Whenever the CSS value currentColor is used as a
color in this API, the "computed value of the 'color' property" for the
purposes of determining the computed value of the currentColor keyword is the computed value of the 'color'
property on the element in question at the time that the color is
specified # 2d.fillStyle.parse.current.basic 2d.fillStyle.parse.current.changed (e.g. when the appropriate attribute is set, or when the method
is called; not when the color is rendered or otherwise used). If the
computed value of the 'color' property is undefined for a particular case
(e.g. because the element is not in a document), then the "computed value
of the 'color' property" for the purposes of determining the computed
value of the currentColor keyword is fully opaque
black # 2d.fillStyle.parse.current.removed . [CSS3COLOR]
Each context maintains a stack of drawing states. Drawing states consist of:
strokeStyle # 2d.state.saverestore.strokeStyle , fillStyle # 2d.state.saverestore.fillStyle ,
globalAlpha # 2d.state.saverestore.globalAlpha , lineWidth # 2d.state.saverestore.lineWidth ,
lineCap # 2d.state.saverestore.lineCap ,
lineJoin # 2d.state.saverestore.lineJoin , miterLimit # 2d.state.saverestore.miterLimit , shadowOffsetX # 2d.state.saverestore.shadowOffsetX , shadowOffsetY # 2d.state.saverestore.shadowOffsetY , shadowBlur # 2d.state.saverestore.shadowBlur , shadowColor # 2d.state.saverestore.shadowColor , globalCompositeOperation # 2d.state.saverestore.globalCompositeOperation ,
font, textAlign,
textBaseline.
The current path # 2d.state.saverestore.path and the current bitmap # 2d.state.saverestore.bitmap are not part of the
drawing state. The current path is persistent, and can only be reset using
the beginPath() method. The current bitmap is
a property of the
canvas, not the context.
The save()
method must push a copy of the current drawing state onto the drawing
state stack # 2d.state.saverestore.stack 2d.state.saverestore.stackdepth .
The restore() method must pop
the top entry in the drawing state stack, and reset the drawing state it
describes # 2d.state.saverestore.stack 2d.state.saverestore.stackdepth . If there is no saved state, the method must do nothing # 2d.state.saverestore.underflow .
The transformation matrix is applied to coordinates when creating shapes and paths.
When the context is created, the transformation matrix must initially be the identity transform. It may then be adjusted using the transformation methods.
The transformations must be performed in reverse order. For instance, if a scale transformation that doubles the width is applied, followed by a rotation transformation that rotates drawing operations by a quarter turn, and a rectangle twice as wide as it is tall is then drawn on the canvas, the actual result will be a square # 2d.transformation.order .
The scale(x, y) method must add the
scaling transformation described by the arguments to the transformation
matrix # 2d.transformation.scale.basic 2d.transformation.scale.zero 2d.transformation.scale.negative 2d.transformation.scale.large . The x argument represents the scale factor in
the horizontal direction and the y argument represents
the scale factor in the vertical direction. The factors are multiples # 2d.transformation.scale.multiple .
The rotate(angle) method must add the rotation
transformation described by the argument to the transformation matrix # 2d.transformation.rotate.zero 2d.transformation.rotate.wrap 2d.transformation.rotate.wrapnegative . The
angle argument represents a clockwise rotation angle # 2d.transformation.rotate.direction
expressed in radians # 2d.transformation.rotate.radians . If the angle argument is
infinite, the method call must be ignored.
The translate(x, y) method must add the translation
transformation described by the arguments to the transformation matrix # 2d.transformation.translate.basic .
The x argument represents the translation distance in
the horizontal direction and the y argument represents
the translation distance in the vertical direction. The arguments are in
coordinate space units.
The transform(m11,
m12, m21, m22,
dx, dy) method must
multiply # 2d.transformation.transform.multiply the current transformation matrix with the matrix described by # 2d.transformation.transform.identity 2d.transformation.transform.skewed :
| m11 | m21 | dx |
| m12 | m22 | dy |
| 0 | 0 | 1 |
The setTransform(m11, m12, m21, m22, dx, dy) method must reset the current transform to
the identity matrix # 2d.transformation.setTransform.multiple , and then invoke the transform(m11, m12, m21, m22, dx, dy) method with the same
arguments # 2d.transformation.setTransform.skewed .
All drawing operations are affected by the global compositing
attributes, globalAlpha and globalCompositeOperation # 2d.composite.operation.get .
The globalAlpha attribute
gives an alpha value that is applied to shapes # 2d.composite.globalAlpha.fill and images # 2d.composite.globalAlpha.image 2d.composite.globalAlpha.canvas 2d.composite.globalAlpha.imagepattern 2d.composite.globalAlpha.canvaspattern before they are
composited onto the canvas. The value must be in the range from 0.0 (fully
transparent) to 1.0 (no additional transparency). If an attempt is made to
set the attribute to a value outside this range, the attribute must retain
its previous value # 2d.composite.globalAlpha.range 2d.composite.globalAlpha.invalid . When the context is created, the globalAlpha attribute must initially have
the value 1.0 # 2d.composite.globalAlpha.default .
The globalCompositeOperation
attribute sets how shapes and images are drawn onto the existing bitmap,
once they have had globalAlpha and the current transformation
matrix applied. It must be set to a value from the following list. In the
descriptions below, the source image, A, is the shape
or image being rendered, and the destination image, B,
is the current state of the bitmap.
source-atop # 2d.composite.solid.source-atop 2d.composite.transparent.source-atop 2d.composite.image.source-atop 2d.composite.canvas.source-atop
source-in # 2d.composite.solid.source-in 2d.composite.transparent.source-in 2d.composite.image.source-in 2d.composite.canvas.source-in 2d.composite.uncovered.fill.source-in 2d.composite.uncovered.image.source-in 2d.composite.uncovered.pattern.source-in
source-out # 2d.composite.solid.source-out 2d.composite.transparent.source-out 2d.composite.image.source-out 2d.composite.canvas.source-out 2d.composite.uncovered.fill.source-out 2d.composite.uncovered.image.source-out 2d.composite.uncovered.pattern.source-out
source-over # 2d.composite.solid.source-over 2d.composite.transparent.source-over 2d.composite.image.source-over 2d.composite.canvas.source-over (default)
destination-atop # 2d.composite.solid.destination-atop 2d.composite.transparent.destination-atop 2d.composite.image.destination-atop 2d.composite.canvas.destination-atop 2d.composite.uncovered.fill.destination-atop 2d.composite.uncovered.image.destination-atop 2d.composite.uncovered.pattern.destination-atop
source-atop but
using the destination image instead of the source image and vice versa.
destination-in # 2d.composite.solid.destination-in 2d.composite.transparent.destination-in 2d.composite.image.destination-in 2d.composite.canvas.destination-in 2d.composite.uncovered.fill.destination-in 2d.composite.uncovered.image.destination-in 2d.composite.uncovered.pattern.destination-in
source-in but using
the destination image instead of the source image and vice versa.
destination-out # 2d.composite.solid.destination-out 2d.composite.transparent.destination-out 2d.composite.image.destination-out 2d.composite.canvas.destination-out
source-out but
using the destination image instead of the source image and vice versa.
destination-over # 2d.composite.solid.destination-over 2d.composite.transparent.destination-over 2d.composite.image.destination-over 2d.composite.canvas.destination-over
source-over but
using the destination image instead of the source image and vice versa.lighter # 2d.composite.solid.lighter 2d.composite.transparent.lighter 2d.composite.image.lighter 2d.composite.canvas.lighter
copy # 2d.composite.solid.copy 2d.composite.transparent.copy 2d.composite.image.copy 2d.composite.canvas.copy 2d.composite.uncovered.fill.copy 2d.composite.uncovered.image.copy 2d.composite.uncovered.pattern.copy
xor # 2d.composite.solid.xor 2d.composite.transparent.xor 2d.composite.image.xor 2d.composite.canvas.xor
vendorName-operationName
These values are all case-sensitive # 2d.composite.operation.casesensitive — they must be used exactly as shown. User agents must not recognize values that do not exactly match the values given above # 2d.composite.operation.nullsuffix .
The operators in the above list must be treated as described by the Porter-Duff operator given at the start of their description (e.g. A over B). [PORTERDUFF]
On setting, if the user agent does not recognize the specified value, it
must be ignored, leaving the value of globalCompositeOperation
unaffected # 2d.composite.operation.unrecognised 2d.composite.operation.darker 2d.composite.operation.over 2d.composite.operation.clear 2d.composite.operation.highlight .
When the context is created, the globalCompositeOperation
attribute must initially have the value source-over # 2d.composite.operation.default .
The strokeStyle attribute
represents the color or style to use for the lines around shapes, and the
fillStyle attribute
represents the color or style to use inside the shapes.
Both attributes can be either strings, CanvasGradients, or CanvasPatterns. On setting, strings must
be parsed as CSS <color> values and the color assigned # 2d.fillStyle.parse.html4 2d.fillStyle.parse.hex3 2d.fillStyle.parse.hex6 2d.fillStyle.parse.rgb-num 2d.fillStyle.parse.rgb-clamp-1 2d.fillStyle.parse.rgb-clamp-2 2d.fillStyle.parse.rgb-clamp-3 2d.fillStyle.parse.rgb-clamp-4 2d.fillStyle.parse.rgb-clamp-5 2d.fillStyle.parse.rgb-percent 2d.fillStyle.parse.rgba-solid-1 2d.fillStyle.parse.rgba-solid-2 2d.fillStyle.parse.rgba-num-1 2d.fillStyle.parse.rgba-num-2 2d.fillStyle.parse.rgba-percent 2d.fillStyle.parse.rgba-clamp-1 2d.fillStyle.parse.rgba-clamp-2 2d.fillStyle.parse.transparent-1 2d.fillStyle.parse.transparent-2 2d.fillStyle.parse.hsl-1 2d.fillStyle.parse.hsl-2 2d.fillStyle.parse.hsl-3 2d.fillStyle.parse.hsl-4 2d.fillStyle.parse.hsl-5 2d.fillStyle.parse.hsl-clamp-1 2d.fillStyle.parse.hsl-clamp-2 2d.fillStyle.parse.hsl-clamp-3 2d.fillStyle.parse.hsl-clamp-4 2d.fillStyle.parse.hsla-1 2d.fillStyle.parse.hsla-2 2d.fillStyle.parse.hsla-clamp-1 2d.fillStyle.parse.hsla-clamp-2 2d.fillStyle.parse.hsla-clamp-3 2d.fillStyle.parse.hsla-clamp-4 2d.fillStyle.parse.hsla-clamp-5 2d.fillStyle.parse.hsla-clamp-6 2d.fillStyle.parse.svg-1 2d.fillStyle.parse.svg-2 2d.fillStyle.parse.invalid.hex3 2d.fillStyle.parse.invalid.hex6 2d.fillStyle.parse.invalid.rgb-1 2d.fillStyle.parse.invalid.rgb-2 2d.fillStyle.parse.invalid.rgb-3 2d.fillStyle.parse.invalid.rgb-4 2d.fillStyle.parse.invalid.rgb-5 2d.fillStyle.parse.invalid.rgb-6 2d.fillStyle.parse.invalid.rgb-7 2d.fillStyle.parse.invalid.rgba-1 2d.fillStyle.parse.invalid.rgba-2 2d.fillStyle.parse.invalid.rgba-3 2d.fillStyle.parse.invalid.rgba-4 2d.fillStyle.parse.invalid.rgba-5 2d.fillStyle.parse.invalid.hsl-1 2d.fillStyle.parse.invalid.hsl-2 2d.fillStyle.parse.invalid.hsl-3 2d.fillStyle.parse.invalid.hsl-4 2d.fillStyle.parse.invalid.hsl-5 2d.fillStyle.parse.invalid.hsla-1 2d.fillStyle.parse.invalid.hsla-2 2d.fillStyle.parse.system 2d.fillStyle.parse.current.basic 2d.fillStyle.parse.current.changed 2d.fillStyle.parse.current.removed , and CanvasGradient and CanvasPattern objects must be assigned
themselves. [CSS3COLOR] If the value is a
string but is not a valid color # 2d.fillStyle.invalidstring , or is neither a string, a CanvasGradient, nor a CanvasPattern # 2d.fillStyle.invalidtype , then it must be ignored,
and the attribute must retain its previous value.
On getting, if the value is a color, then the serialization of the color must be
returned. Otherwise, if it is not a color but a CanvasGradient # 2d.gradient.object.compare or CanvasPattern # , then the respective
object must be returned. (Such objects are opaque and therefore only
useful for assigning to other attributes or for comparison to other
gradients or patterns.)
The serialization of a color for a color
value is a string, computed as follows: if it has alpha equal to 1.0, then
the string is a lowercase six-digit hex value # 2d.fillStyle.get.solid , prefixed with a "#"
character (U+0023 NUMBER SIGN), with the first two digits representing the
red component, the next two digits representing the green component, and
the last two digits representing the blue component, the digits being in
the range 0-9 a-f (U+0030 to U+0039 and U+0061 to U+0066). Otherwise, the
color value has alpha less than 1.0, and the string is the color value in
the CSS rgba() functional-notation format: the
literal string rgba (U+0072 U+0067 U+0062 U+0061)
followed by a U+0028 LEFT PARENTHESIS, a base-ten integer in the range
0-255 representing the red component (using digits 0-9, U+0030 to U+0039,
in the shortest form possible), a literal U+002C COMMA and U+0020 SPACE,
an integer for the green component, a comma and a space, an integer for
the blue component, another comma and space, a U+0030 DIGIT ZERO, a U+002E
FULL STOP (representing the decimal point), one or more digits in the
range 0-9 (U+0030 to U+0039) representing the fractional part of the alpha
value, and finally a U+0029 RIGHT PARENTHESIS # 2d.fillStyle.get.semitransparent 2d.fillStyle.get.transparent .
When the context is created, the strokeStyle and fillStyle
attributes must initially have the string value #000000 # 2d.fillStyle.default 2d.strokeStyle.default .
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. The color of the gradient at each stop is the color specified for that stop. Between each such stop, the colors and the alpha component must be linearly interpolated # 2d.gradient.interpolate.solid 2d.gradient.interpolate.colour 2d.gradient.interpolate.alpha 2d.gradient.interpolate.vertical 2d.gradient.interpolate.multiple over the RGBA space without premultiplying the alpha value # 2d.gradient.interpolate.colouralpha to find the color to use at that offset. Before the first stop, the color must be the color of the first stop # 2d.gradient.interpolate.outside . After the last stop, the color must be the color of the last stop # 2d.gradient.interpolate.outside . When there are no stops, the gradient is transparent black # 2d.gradient.empty .
The addColorStop(offset, color) method on
the CanvasGradient interface
adds a new stop to a gradient. If the offset is less
than 0, greater than 1, infinite, or NaN, then an
INDEX_SIZE_ERR exception must be raised # 2d.gradient.object.invalidoffset . If the color cannot be parsed as a CSS color, then a
SYNTAX_ERR exception must be raised # 2d.gradient.object.invalidcolour . Otherwise, the gradient
must have a new stop placed, at offset offset relative
to the whole gradient, and with the color obtained by parsing color as a CSS <color> value # 2d.gradient.object.update . If multiple stops are
added at the same offset on a gradient, they must be placed in the order
added, with the first one closest to the start of the gradient, and each
subsequent one infinitesimally further along towards the end point (in
effect causing all but the first and last stop added at each point to be
ignored) # 2d.gradient.interpolate.overlap 2d.gradient.interpolate.overlap2 .
The createLinearGradient(x0, y0, x1, y1) method takes four arguments that represent
the start point (x0, y0) and end
point (x1, y1) of the gradient. If
any of the arguments to createLinearGradient() are
infinite or NaN, the method must raise a NOT_SUPPORTED_ERR
exception # 2d.gradient.linear.nonfinite . Otherwise, the method must return a linear CanvasGradient # 2d.gradient.object.return initialized with the
specified line.
Linear gradients must be rendered such that all points on a line perpendicular to the line that crosses the start and end points have the color at the point where those two lines cross (with the colors coming from the interpolation and extrapolation described above). The points in the linear gradient must be transformed as described by the current transformation matrix when rendering # 2d.gradient.linear.transform.1 2d.gradient.linear.transform.2 2d.gradient.linear.transform.3 .
If x0 = x1 and y0 = y1, then the linear gradient must paint nothing # 2d.gradient.interpolate.zerosize .
The createRadialGradient(x0, y0, r0, x1, y1, r1) method takes six arguments, the first
three representing the start circle with origin (x0,
y0) and radius r0, and the last
three representing the end circle with origin (x1,
y1) and radius r1. The values are
in coordinate space units. If any of the arguments are infinite or NaN, a
NOT_SUPPORTED_ERR exception must be raised # 2d.gradient.radial.nonfinite . If either of r0 or r1 are negative, an
INDEX_SIZE_ERR exception must be raised # 2d.gradient.radial.negative . Otherwise, the
method must return a radial CanvasGradient # 2d.gradient.object.return initialized with the two
specified circles.
Radial gradients must be rendered by following these steps # 2d.gradient.radial.inside1 2d.gradient.radial.inside2 2d.gradient.radial.inside3 2d.gradient.radial.outside1 2d.gradient.radial.outside2 2d.gradient.radial.outside3 2d.gradient.radial.touch1 2d.gradient.radial.touch2 2d.gradient.radial.touch3 2d.gradient.radial.cone.behind 2d.gradient.radial.cone.front 2d.gradient.radial.cone.bottom 2d.gradient.radial.cone.top 2d.gradient.radial.cone.beside 2d.gradient.radial.cone.cylinder 2d.gradient.radial.cone.shape1 2d.gradient.radial.cone.shape2 :
If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing # 2d.gradient.radial.equal . Abort these steps.
Let x(ω) = (x1-x0)ω + x0
Let y(ω) = (y1-y0)ω + y0
Let r(ω) = (r1-r0)ω + r0
Let the color at ω be the color at that position on the gradient (with the colors coming from the interpolation and extrapolation described above).
For all values of ω where r(ω) > 0, starting with the value of ω nearest to positive infinity and ending with the value of ω nearest to negative infinity, draw the circumference of the circle with radius r(ω) at position (x(ω), y(ω)), with the color at ω, but only painting on the parts of the canvas that have not yet been painted on by earlier circles in this step for this rendering of the gradient.
This effectively creates a cone, touched by the two circles defined in the creation of the gradient, with the part of the cone before the start circle (0.0) using the color of the first offset, the part of the cone after the end circle (1.0) using the color of the last offset, and areas outside the cone untouched by the gradient (transparent black).
Gradients must be painted only where the relevant stroking or filling effects requires that they be drawn.
The points in the radial gradient must be transformed as described by the current transformation matrix when rendering # 2d.gradient.radial.transform.1 2d.gradient.radial.transform.2 2d.gradient.radial.transform.3 .
Patterns are represented by objects implementing the opaque CanvasPattern interface.
To create objects of this type, the createPattern(image, repetition) method
is used. The first argument gives the image to use as the pattern (either
an HTMLImageElement or an
HTMLCanvasElement).
Modifying this image after calling the createPattern() method must not affect
the pattern # 2d.pattern.modify.image1 2d.pattern.modify.image2 2d.pattern.modify.canvas1 2d.pattern.modify.canvas2 . The second argument must be a string with one of the
following values: repeat, repeat-x, repeat-y, no-repeat. If the empty string or null is specified, repeat must be assumed # 2d.pattern.repeat.empty 2d.pattern.repeat.null . If an unrecognized value is given,
then the user agent must raise a SYNTAX_ERR exception # 2d.pattern.repeat.undefined 2d.pattern.repeat.unrecognised . User
agents must recognize the four values described above exactly (e.g. they
must not do case folding) # 2d.pattern.repeat.case 2d.pattern.repeat.nullsuffix . The method must return a CanvasPattern object suitably
initialized # 2d.pattern.basic.type .
The image argument must be an instance of an
HTMLImageElement or HTMLCanvasElement. If the image is of the wrong type or null, the implementation must
raise a TYPE_MISMATCH_ERR exception # 2d.pattern.image.undefined 2d.pattern.image.null 2d.pattern.image.string .
If the image argument is an HTMLImageElement object whose complete attribute
is false, then the implementation must raise an
INVALID_STATE_ERR exception # 2d.pattern.image.incomplete 2d.pattern.image.broken .
If the image argument is an HTMLCanvasElement object with either
a horizontal dimension or a vertical dimension equal to zero, then the
implementation must raise an INVALID_STATE_ERR exception # 2d.pattern.basic.zerocanvas .
Patterns must be painted so that the top left of the first image is
anchored at the origin of the coordinate space, and images are then
repeated horizontally to the left and right (if the repeat-x
string was specified) or vertically up and down (if the
repeat-y string was specified) or in all four directions all
over the canvas (if the repeat string was specified) # 2d.pattern.basic.image 2d.pattern.basic.canvas 2d.pattern.basic.nocontext 2d.pattern.paint.norepeat.basic 2d.pattern.paint.norepeat.outside 2d.pattern.paint.norepeat.coord1 2d.pattern.paint.norepeat.coord2 2d.pattern.paint.norepeat.coord3 2d.pattern.paint.repeat.basic 2d.pattern.paint.repeat.outside 2d.pattern.paint.repeat.coord1 2d.pattern.paint.repeat.coord2 2d.pattern.paint.repeat.coord3 2d.pattern.paint.repeatx.basic 2d.pattern.paint.repeatx.outside 2d.pattern.paint.repeatx.coord1 2d.pattern.paint.repeaty.basic 2d.pattern.paint.repeaty.outside 2d.pattern.paint.repeaty.coord1 2d.pattern.paint.orientation.image 2d.pattern.paint.orientation.canvas . The
images are not scaled by this process; one CSS pixel of the image must be
painted on one coordinate space unit # . Of course, patterns must actually be
painted only where the stroking or filling effect requires that they be
drawn # , and are affected by the current transformation matrix.
When the createPattern() method is passed, as its
image argument, an animated image, the poster frame of
the animation, or the first frame of the animation if there is no poster
frame, must be used # 2d.pattern.animated.gif .
Support for patterns is optional. If the user agent doesn't support
patterns, then createPattern() must return null # .
The lineWidth attribute
gives the width of lines, in coordinate space units # 2d.line.width.basic 2d.line.width.transformed . On setting, zero,
negative, infinite, and NaN values must be ignored, leaving the value
unchanged # 2d.line.width.invalid .
When the context is created, the lineWidth attribute must initially have the
value 1.0 # 2d.line.defaults .
The lineCap attribute defines
the type of endings that UAs will place on the end of lines # 2d.line.cap.open 2d.line.cap.closed . The three
valid values are butt, round, and
square. The butt value means that the end of
each line has a flat edge perpendicular to the direction of the line (and
that no additional line cap is added) # 2d.line.cap.butt . The round value means
that a semi-circle with the diameter equal to the width of the line must
then be added on to the end of the line # 2d.line.cap.round . The square value
means that a rectangle with the length of the line width and the width of
half the line width, placed flat against the edge perpendicular to the
direction of the line, must be added at the end of each line # 2d.line.cap.square . On setting,
any other value than the literal strings butt,
round, and square must be ignored, leaving the
value unchanged # 2d.line.cap.invalid .
When the context is created, the lineCap attribute must initially have the value
butt # 2d.line.defaults .
The lineJoin attribute
defines the type of corners that UAs will place where two lines meet. The
three valid values are bevel, round, and
miter.
On setting, any other value than the literal strings bevel,
round, and miter must be ignored, leaving the
value unchanged # 2d.line.join.invalid .
When the context is created, the lineJoin attribute must initially have the
value miter # 2d.line.defaults .
A join exists at any point in a subpath shared by two consecutive lines # 2d.line.join.open 2d.line.join.parallel . When a subpath is closed, then a join also exists at its first point (equivalent to its last point) connecting the first and last lines in the subpath # 2d.line.join.closed .
In addition to the point where the join occurs, two additional points are relevant to each join, one for each line: the two corners found half the line width away from the join point, one perpendicular to each line, each on the side furthest from the other line.
A filled triangle connecting these two opposite corners with a straight
line, with the third point of the triangle being the join point, must be
rendered at all joins # 2d.line.join.bevel . The lineJoin attribute controls whether anything
else is rendered. The three aforementioned values have the following
meanings:
The bevel value means that this is all that is rendered at
joins # 2d.line.join.bevel .
The round value means that a filled arc connecting the two
aforementioned corners of the join, abutting (and not overlapping) the
aforementioned triangle, with the diameter equal to the line width and the
origin at the point of the join, must be rendered at joins # 2d.line.join.round .
The miter value means that a second filled triangle must
(if it can given the miter length) be rendered at the join, with one line
being the line between the two aforementioned corners, abutting the first
triangle, and the other two being continuations of the outside edges of
the two joining lines, as long as required to intersect without going over
the miter length # 2d.line.join.miter 2d.line.miter.exceeded 2d.line.miter.acute 2d.line.miter.obtuse 2d.line.miter.rightangle 2d.line.miter.lineedge 2d.line.miter.within .
The miter length is the distance from the point where the lines touch on the inside of the join to the intersection of the line edges on the outside of the join. The miter limit ratio is the maximum allowed ratio of the miter length to half the line width. If the miter length would cause the miter limit ratio to be exceeded, this second triangle must not be rendered # 2d.line.miter.exceeded 2d.line.miter.acute 2d.line.miter.obtuse .
The miter limit ratio can be explicitly set using the miterLimit attribute.
On setting, zero, negative, infinite, and NaN values must be ignored,
leaving the value unchanged # 2d.line.miter.invalid .
When the context is created, the miterLimit attribute must initially have the
value 10.0 # 2d.line.defaults .
All drawing operations are affected by the four global shadow attributes.
The shadowColor attribute
sets the color of the shadow.
When the context is created, the shadowColor attribute initially must be
fully-transparent black.
On getting, the serialization of the color must be returned.
On setting, the new value must be parsed as a CSS <color> value and the color assigned. If the value is not a valid color, then it must be ignored, and the attribute must retain its previous value. [CSS3COLOR]
The shadowOffsetX and
shadowOffsetY
attributes specify the distance that the shadow will be offset in the
positive horizontal and positive vertical distance respectively. Their
values are in coordinate space units. They are not affected by the current
transformation matrix.
When the context is created, the shadow offset attributes must initially
have the value 0.
On getting, they must return their current value. On setting, the attribute being set must be set to the new value, except if the value is infinite or NaN, in which case the new value must be ignored.
The shadowBlur attribute
specifies the size of the blurring effect. (The units do not map to
coordinate space units, and are not affected by the current transformation
matrix.)
When the context is created, the shadowBlur attribute must initially have the
value 0.
On getting, the attribute must return its current value. On setting the attribute must be set to the new value, except if the value is negative, infinite or NaN, in which case the new value must be ignored.
When shadows are drawn, they must be rendered as follows:
Let A be the source image for which a shadow is being created.
Let B be an infinite transparent black bitmap, with a coordinate space and an origin identical to A.
Copy the alpha channel of A to B, offset by shadowOffsetX in the positive x direction, and shadowOffsetY in the positive y direction.
If shadowBlur is greater than 0:
If shadowBlur is less than 8, let σ be half the value of shadowBlur; otherwise, let σ be the square root of multiplying the value of
shadowBlur by 2.
Perform a 2D Gaussian Blur on B, using σ as the standard deviation.
User agents may limit values of σ to an implementation-specific maximum value to avoid exceeding hardware limitations during the Gaussian blur operation.
Set the red, green, and blue components of every pixel in B to the red, green, and blue components (respectively)
of the color of shadowColor.
Multiply the alpha component of every pixel in B
by the alpha component of the color of shadowColor.
The shadow is in the bitmap B, and is rendered as part of the drawing model described below.
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.
The current transformation matrix must be applied to the following four coordinates, which form the path that must then be closed to get the specified rectangle: (x, y), (x+w, y), (x+w, y+h), (x, y+h).
Shapes are painted without affecting the current path, and are subject
to the clipping region,
and, with the exception of clearRect(), also shadow effects, global alpha, and global composition
operators.
The clearRect(x, y, w, h) method must clear the pixels in the
specified rectangle that also intersect the current clipping region to a
fully transparent black, erasing any previous image # 2d.clearRect.basic 2d.clearRect.path 2d.clearRect.zero 2d.clearRect.negative 2d.clearRect.transform 2d.clearRect.globalalpha 2d.clearRect.globalcomposite 2d.clearRect.clip 2d.clearRect.shadow . If either height or
width are zero, this method has no effect.
The fillRect(x, y, w, h) method must paint the specified rectangular
area using the fillStyle # 2d.fillRect.basic 2d.fillRect.path 2d.fillRect.zero 2d.fillRect.negative 2d.fillRect.transform 2d.fillRect.clip 2d.fillRect.shadow . If either height or width are
zero, this method has no effect.
The strokeRect(x,
y, w, h) method must stroke the specified
rectangle's path using the strokeStyle, lineWidth,
lineJoin, and (if appropriate) miterLimit attributes # 2d.strokeRect.basic 2d.strokeRect.path 2d.strokeRect.zero.1 2d.strokeRect.zero.2 2d.strokeRect.zero.3 2d.strokeRect.zero.4 2d.strokeRect.zero.5 2d.strokeRect.negative 2d.strokeRect.transform 2d.strokeRect.globalalpha 2d.strokeRect.globalcomposite 2d.strokeRect.clip 2d.strokeRect.shadow . If both height and
width are zero, this method has no effect, since there is no path to
stroke (it's a point). If only one of the two is zero, then the method
will draw a line instead (the path for the outline is just a straight line
along the non-zero dimension).
The context always has a current path. There is only one current path, it is not part of the drawing state.
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.
Initially, the context's path must have zero subpaths # 2d.path.initial .
The points and lines added to the path by these methods must be transformed according to the current transformation matrix as they are added # 2d.path.arc.scale.1 2d.path.stroke.scale1 2d.path.stroke.scale2 2d.path.stroke.skew 2d.path.transformation.basic 2d.path.transformation.multiple 2d.path.transformation.changing .
The beginPath() method must
empty the list of subpaths so that the context once again has zero
subpaths # 2d.path.beginPath .
The moveTo(x, y) method must create a
new subpath with the specified point as its first (and only) point # 2d.path.moveTo.basic 2d.path.moveTo.newsubpath 2d.path.moveTo.multiple .
The closePath() method must
do nothing if the context has no subpaths # 2d.path.closePath.empty . Otherwise, it must mark the
last subpath as closed, create a new subpath whose first point is the same
as the previous subpath's first point, and finally add this new subpath to
the path # 2d.path.closePath.newline 2d.path.closePath.nextpoint . (If the last subpath had more than one point in its list of
points, then this is equivalent to adding a straight line connecting the
last point back to the first point, thus "closing" the shape, and then
repeating the last moveTo() call.)
New points and the lines connecting them are added to subpaths using the methods described below. In all cases, the methods only modify the last subpath in the context's paths.
The lineTo(x, y) method must do
nothing if the context has no subpaths # 2d.path.lineTo.emptysubpath . Otherwise, it must connect the
last point in the subpath to the given point (x, y) using a straight line, and must then add the given point
(x, y) to the subpath # 2d.path.lineTo.basic 2d.path.lineTo.nextpoint .
The quadraticCurveTo(cpx, cpy, x, y) method must do nothing if the context has
no subpaths # 2d.path.quadraticCurveTo.emptysubpath . Otherwise it must connect the last point in the subpath to
the given point (x, y) using a
quadratic Bézier curve with control point (cpx,
cpy), and must then add the given point (x, y) to the subpath # 2d.path.quadraticCurveTo.basic 2d.path.quadraticCurveTo.shape 2d.path.quadraticCurveTo.scaled . [BEZIER]
The bezierCurveTo(cp1x, cp1y, cp2x,
cp2y, x, y) method must do nothing if the context has
no subpaths # 2d.path.bezierCurveTo.emptysubpath . Otherwise, it must connect the last point in the subpath to
the given point (x, y) using a
cubic Bézier curve with control points (cp1x