canvas
elementStrictly inline-level embedded content.
figure
element.
height
width
interface HTMLCanvasElement : HTMLElement { attribute long width; size.width size.attributes size.attributes.type.get size.attributes.type.set attribute long height; size.height size.attributes size.attributes.type.get size.attributes.type.set DOMString toDataURL(); DOMString toDataURL(in DOMString type); DOMObject getContext(in DOMString contextID); };
Shouldn't allow inline-level content to be the content model when the parent's content model is strictly inline only.
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.
In interactive visual media with scripting enabled, the canvas element is 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 must be treated as embedded
content with the current image and size. Otherwise, the element's fallback
content must be used instead.
In non-visual media, and in visual media with scripting
disabled, the canvas
element's
fallback content must be used instead.
The canvas
element has two attributes
to control the size of the coordinate space: height
and width
. 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.nonnegativeinteger size.attributes.parse.whitespace size.attributes.parse.nonnumber size.attributes.parse.zero size.attributes.parse.negative size.attributes.parse.floatsuffix.zero size.attributes.parse.floatsuffix.nonzero size.attributes.parse.badsuffix . If an attribute is missing size.missing size.attributes.default size.attributes.removed , or if parsing its
value returns an error size.error size.attributes.parse.nonnumber size.attributes.parse.negative , then the default value must be used instead. The
width
attribute defaults to 300, and the height
attribute defaults to 150 size.default 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.css 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.
The canvas must initially be fully transparent black initial.colour initial.colour .
If the width
and height
attributes are dynamically modified, the bitmap and any associated
contexts must be cleared back to their initial state initial.reset initial.reset.different initial.reset.same and reinitialised
with the newly specified coordinate space dimensions.
The width
and
height
DOM
attributes must reflect the content attributes of
the same name size.reflect size.attributes.reflect.1 size.attributes.reflect.2 .
To draw on the canvas, authors must first obtain a reference to a context using the getContext
method of the
canvas
element.
This specification only defines one context, with the name "2d
". If getContext()
is called with that exact string, then the UA must return a reference to
an object implementing CanvasRenderingContext2D
context.2d 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.empty context.empty or a string specifying a context that it does not support context.unrecognised context.unrecognised.badname context.unrecognised.badsuffix context.unrecognised.nullsuffix context.unrecognised.unicode , then it must return null. String comparisons should be literal and case-sensitive context.casesensitive context.casesensitive .
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. [PNG].
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. 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.
User agents must convert the provided type to lower case before
establishing if they support that type and before creating the
data:
URL.
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.
Arguments other than the type 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). 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.
Security: To prevent information leakage, the
toDataURL()
and getImageData()
methods should raise a security exception if the canvas ever had images
painted on it that originate from a domain other than the domain of the script that
painted the images onto the canvas.
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 context.2d.unique 2d.getcontext.unique .
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 2d.coordinatespace .
interface CanvasRenderingContext2D { // back-reference to the canvas readonly attribute 2d.canvas.attribute 2d.canvas.readonly 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 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, DOMString repetition); CanvasPattern createPattern(in HTMLCanvasElement image, 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 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); // 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 getImageData(in float sx, in float sy, in float sw, in float sh); void putImageData(in ImageData image, in float dx, in float dy); // drawing text is not supported in this version of the API // (there is no way to predict what metrics the fonts will have, // which makes fonts very hard to use for painting) }; interface CanvasGradient { // opaque object void addColorStop(in float offset, in DOMString color); }; interface CanvasPattern { // opaque object }; interface ImageData { readonly attribute long int width; readonly attribute long int height; readonly attribute int[] data; };
The canvas
attribute must
return the canvas
element that the
context paints on 2d.canvas 2d.canvas.reference .
Each context maintains a stack of drawing states. Drawing states consist of:
strokeStyle
2d.state.strokeStyle 2d.state.saverestore.strokeStyle , fillStyle
2d.state.fillStyle 2d.state.saverestore.fillStyle ,
globalAlpha
2d.state.globalAlpha 2d.state.saverestore.globalAlpha , lineWidth
2d.state.lineWidth 2d.state.saverestore.lineWidth ,
lineCap
2d.state.lineCap 2d.state.saverestore.lineCap ,
lineJoin
2d.state.lineJoin 2d.state.saverestore.lineJoin , miterLimit
2d.state.miterLimit 2d.state.saverestore.miterLimit , shadowOffsetX
2d.state.shadowOffsetX 2d.state.saverestore.shadowOffsetX , shadowOffsetY
2d.state.shadowOffsetY 2d.state.saverestore.shadowOffsetY , shadowBlur
2d.state.shadowBlur 2d.state.saverestore.shadowBlur , shadowColor
2d.state.shadowColor 2d.state.saverestore.shadowColor , globalCompositeOperation
2d.state.globalCompositeOperation 2d.state.saverestore.globalCompositeOperation .
The current path 2d.state.path 2d.state.saverestore.path and the current bitmap 2d.state.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 pushes a copy of the current drawing state onto the drawing state
stack 2d.state.save 2d.state.saverestore.stack 2d.state.saverestore.stackdepth .
The restore()
method pops the
top entry in the drawing state stack, and resets the drawing state it
describes 2d.state.restore 2d.state.saverestore.stack 2d.state.saverestore.stackdepth . If there is no saved state, the method does nothing 2d.state.restore.underflow 2d.state.saverestore.underflow .
The transformation matrix is applied to all drawing operations prior to their being rendered. It is also applied when creating the clip region.
When the context is created, the transformation matrix must initially be the identity transform. It may then be adjusted using the three 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 2d.transformation.order .
The scale(x, y)
method must add the
scaling transformation described by the arguments to the transformation
matrix 2d.transformation.scale 2d.transformation.scale.basic 2d.transformation.scale.zero 2d.transformation.scale.negative 2d.transformation.scale.large 2d.transformation.scale.inf 2d.transformation.scale.neginf 2d.transformation.scale.nan . 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.
The rotate(angle)
method must add the rotation
transformation described by the argument to the transformation matrix 2d.transformation.rotate 2d.transformation.rotate.zero 2d.transformation.rotate.wrap 2d.transformation.rotate.wrapnegative 2d.transformation.rotate.inf 2d.transformation.rotate.neginf 2d.transformation.rotate.nan . The
angle argument represents a clockwise rotation angle 2d.transformation.rotate.direction 2d.transformation.rotate.direction
expressed in radians 2d.transformation.rotate.radians 2d.transformation.rotate.radians .
The translate(x, y)
method must add the translation
transformation described by the arguments to the transformation matrix 2d.transformation.translate .
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 the current transformation matrix with the matrix described by:
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, and then invoke the transform(m11, m12, m21, m22, dx, dy)
method with the same
arguments.
All drawing operations are affected by the global compositing
attributes, globalAlpha
and globalCompositeOperation
.
The globalAlpha
attribute
gives an alpha value that is applied to shapes and images 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. When the context is created, the globalAlpha
attribute must initially have
the value 1.0.
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 is the shape or image being rendered,
and the destination image is the current state of the bitmap.
The source-* descriptions below don't define what should happen with semi-transparent regions.
source-atop
source-in
source-out
source-over
(default)
destination-atop
source-atop
but using the destination
image instead of the source image and vice versa.
destination-in
source-in
but using the destination image
instead of the source image and vice versa.
destination-out
source-out
but using the destination image
instead of the source image and vice versa.
destination-over
source-over
but using the destination
image instead of the source image and vice versa.
darker
lighter
copy
xor
vendorName-operationName
These values are all case-sensitive — they must be used exactly as shown. User agents must only recognise values that exactly match the values given above.
On setting, if the user agent does not recognise the specified value, it
must be ignored, leaving the value of globalCompositeOperation
unaffected.
When the context is created, the globalCompositeOperation
attribute must initially have the value source-over
.
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, CanvasGradient
s, or CanvasPattern
s. On setting, strings
should be parsed as CSS <color> values and the color assigned, and
CanvasGradient
and CanvasPattern
objects must be assigned
themselves. [CSS3COLOR] If the value is a
string but is not a valid color, or is neither a string, a CanvasGradient
, nor a CanvasPattern
, then it must be ignored,
and the attribute must retain its previous value.
On getting, if the value is a color, then: if it has alpha equal to 1.0,
then the color must be returned as an uppercase six-digit hex value,
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+0041 to U+0046). If the value has alpha less than 1.0, then the value
must instead be returned 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.
Otherwise, if it is not a color but a CanvasGradient
or CanvasPattern
, then an object supporting
those interfaces must be returned. Such objects are opaque and therefore
only useful for assigning to other attributes or for comparison to other
gradients or patterns.
When the context is created, the strokeStyle
and fillStyle
attributes must initially have the string value #000000
.
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 must be placed along it to define how the colors are distributed along the gradient. Between each such stop, the colors and the alpha component must be interpolated over the RGBA space to find the color to use at that offset. Immediately before the 0 offset and immediately after the 1 offset, transparent black stops are be assumed.
The addColorStop(offset, color)
method on
the CanvasGradient
interface
adds a new stop to a gradient. If the offset is less
than 0 or greater than 1 then an INDEX_SIZE_ERR
exception
must be raised. If the color cannot be parsed as a CSS
color, then a SYNTAX_ERR
exception must be raised. Otherwise,
the gradient must be updated with the new stop information.
The createLinearGradient(x0, y0, x1, y1)
method takes four arguments, representing
the start point (x0, y0) and end
point (x1, y1) of the gradient, in
coordinate space units, and must return a linear CanvasGradient
initialised with that
line.
Linear gradients must be rendered such that at the starting point on the canvas the color at offset 0 is used, that at the ending point the color at offset 1 is used, that all points on a line perpendicular to the line between the start and end points have the color at the point where those two lines cross (interpolation happening as described above), and that any points beyond the start or end points are a transparent black.
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. The method must return a radial CanvasGradient
initialised with those
two circles.
Radial gradients must be rendered such that a cone is created from the two circles, so that at the circumference of the starting circle the color at offset 0 is used, that at the circumference around the ending circle the color at offset 1 is used, that the circumference of a circle drawn a certain fraction of the way along the line between the two origins with a radius the same fraction of the way between the two radii has the color at that offset (interpolation happening as described above), that the end circle appear to be above the start circle when the end circle is not completely enclosed by the start circle, that the end circle be filled by the color at offset 1, and that any points not described by the gradient are a transparent black.
If a gradient has no stops defined, then the gradient must be treated as a solid transparent black. Gradients are, naturally, only painted where the stroking or filling effect requires that they be drawn.
Support for actually painting gradients is optional. Instead of painting
the gradients, user agents may instead just paint the first stop's color.
However, createLinearGradient()
and createRadialGradient()
must always return objects when passed valid arguments.
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. 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. If an unrecognised value is given,
then the user agent must raise a SYNTAX_ERR
exception. User
agents must recognise the four values described above exactly (e.g. they
must not do case folding). The method must return a CanvasPattern
object suitably
initialised.
The image argument must be an instance of an
HTMLImageElement
or HTMLCanvasElement
. If the image is of the wrong type, the implementation must raise a
TYPE_MISMATCH_ERR
exception.
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). The
images are not be scaled by this process; one CSS pixel of the image must
be painted on one coordinate space unit. Of course, patterns must only
actually painted where the stroking or filling effect requires that they
be drawn, and are affected by the current transformation matrix.
Support for patterns is optional. If the user agent doesn't support
patterns, then createPattern()
must return
null.
The lineWidth
attribute
gives the default width of lines, in coordinate space units. On setting,
zero and negative values must be ignored, leaving the value unchanged.
When the context is created, the lineWidth
attribute must initially have the
value 1.0
.
The lineCap
attribute defines
the type of endings that UAs shall place on the end of lines. The three
valid values are butt
, round
, and
square
. The butt
value means that the end of
each line is a flat edge perpendicular to the direction of the line. The
round
value means that a semi-circle with the diameter equal
to the width of the line is then added on to the end of the line. The
square
value means that at the end of each line is 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. On setting, any other value than the literal strings
butt
, round
, and square
must be
ignored, leaving the value unchanged.
When the context is created, the lineCap
attribute must initially have the value
butt
.
The lineJoin
attribute
defines the type of corners that that UAs will place where two lines meet.
The three valid values are round
, bevel
, and
miter
.
On setting, any other value than the literal strings round
,
bevel
and miter
must be ignored, leaving the
value unchanged.
When the context is created, the lineJoin
attribute must initially have the
value miter
.
The round
value means that a filled arc connecting the
corners on the outside of the join, with the diameter equal to the line
width, and the origin at the point where the inside edges of the lines
touch, must be rendered at joins. The bevel
value means that
a filled triangle connecting those two corners with a straight line, the
third point of the triangle being the point where the lines touch on the
inside of the join, must be rendered at joins. The miter
value means that a filled four- or five-sided polygon must be placed at
the join, with two of the lines being the perpendicular edges of the
joining lines, 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 limit.
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 the line width. If the miter limit would be exceeded, then a fifth line must be added to the polygon, connecting the two outside lines, such that the distance from the inside point of the join to the point in the middle of this fifth line is the maximum allowed value for the miter length.
The miter limit ratio can be explicitly set using the miterLimit
attribute.
On setting, zero and negative values must be ignored, leaving the value
unchanged.
When the context is created, the miterLimit
attribute must initially have the
value 10.0
.
All drawing operations are affected by the four global shadow attributes. Shadows form part of the source image during composition.
The shadowColor
attribute
sets the color of the shadow.
When the context is created, the shadowColor
attribute initially must be
fully-transparent black.
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.
When the context is created, the shadow offset attributes initially have
the value 0
.
The shadowBlur
attribute
specifies the number of coordinate space units that the blurring is to
cover. On setting, negative numbers must be ignored, leaving the attribute
unmodified.
When the context is created, the shadowBlur
attribute must initially have the
value 0
.
Support for shadows is optional. When they are supported, then, when shadows are drawn, they must be rendered using the specified color, offset, and blur radius.
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 and height of the rectangle, respectively.
Shapes are painted without affecting the current path, and are subject to transformations, shadow effects, global alpha, clipping paths, and global composition operators.
Negative values for width and height must cause the implementation to
raise an INDEX_SIZE_ERR
exception.
The clearRect()
method must
clear the pixels in the specified rectangle to a fully transparent black,
erasing any previous image. If either height or width are zero, this
method has no effect.
The fillRect()
method must
paint the specified rectangular area using the fillStyle
.
If either height or width are zero, this method has no effect.
The strokeRect()
method
must draw a rectangular outline of the specified size using the strokeStyle
, lineWidth
,
lineJoin
, and (if appropriate) miterLimit
attributes. What should happen with zero heights or widths?
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.
The beginPath()
method must
empty the list of subpaths so that the context once again has zero
subpaths.
The moveTo(x, y)
method must create a
new subpath with the specified point as its first (and only) point.
The closePath()
method must
do nothing if the context has no subpaths. 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. (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. 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.
The quadraticCurveTo(cpx, cpy, x, y)
method must do nothing if the context has
no subpaths. Otherwise it must connect the last point in the subpath to
the given point (x, y) by a
quadratic curve with control point (cpx, cpy), and must then add the given point (x, y) to the subpath.
The bezierCurveTo(cp1x, cp1y, cp2x,
cp2y, x, y)
method must do nothing if the context has
no subpaths. Otherwise, it must connect the last point in the subpath to
the given point (x, y) using a
bezier curve with control points (cp1x, cp1y) and (cp2x, cp2y). Then, it must add the point (x,
y) to the subpath.
The arcTo(x1, y1, x2, y2, radius)
method must do
nothing if the context has no subpaths. If the context does have
a subpath, then the behaviour depends on the arguments and the last point
in the subpath.
Let the point (x0, y0) be the last point in the subpath. Let The Arc be the shortest arc given by circumference of the circle that has one point tangent to the line defined by the points (x0, y0) and (x1, y1), another point tangent to the line defined by the points (x1, y1) and (x2, y2), and that has radius radius. The points at which this circle touches these two lines are called the start and end tangent points respectively.
If the point (x2, y2) is on the line defined by the points (x0, y0) and (x1, y1) then the method must do nothing, as no arc would satisfy the above constraints.
Otherwise, the method must connect the point (x0, y0) to the start tangent point by a straight line, then connect the start tangent point to the end tangent point by The Arc, and finally add the start and end tangent points to the subpath.
Negative or zero values for radius must cause the
implementation to raise an INDEX_SIZE_ERR
exception.
The arc(x, y, radius, startAngle, endAngle, anticlockwise)
method draws an arc. If the
context has any subpaths, then the method must add a straight line from
the last point in the subpath to the start point of the arc. In any case,
it must draw the arc between the start point of the arc and the end point
of the arc, and add the start and end points of the arc to the subpath.
The arc and its start and end points are defined as follows:
Consider a circle that has its origin at (x, y) and that has radius radius. The points at startAngle and endAngle along the circle's circumference, measured in radians clockwise from the positive x-axis, are the start and end points respectively. The arc is the path along the circumference of this circle from the start point to the end point, going anti-clockwise if the anticlockwise argument is true, and clockwise otherwise.
Negative or zero values for radius must cause the
implementation to raise an INDEX_SIZE_ERR
exception.
The rect(x, y, w, h)
method must create a new subpath containing
just the four points (x, y), (x+w, y), (x+w, y+h), (x, y+h), with those four points connected by straight lines, and
must then mark the subpath as closed. It must then create a new subpath
with the point (x, y) as the only
point in the subpath.
Negative values for w and h must
cause the implementation to raise an INDEX_SIZE_ERR
exception.
The fill()
method must fill each subpath of the current path in turn, using fillStyle
,
and using the non-zero winding number rule. Open subpaths must be
implicitly closed when being filled (without affecting the actual
subpaths).
The stroke()
method must stroke
each subpath of the current path in turn, using the strokeStyle
, lineWidth
,
lineJoin
, and (if appropriate) miterLimit
attributes.
Paths, when filled or stroked, must be painted without affecting the current path, and must be subject to transformations, shadow effects, global alpha, clipping paths, and global composition operators.
The transformation is applied to the path when it is drawn, not when the path is constructed. Thus, a single path can be constructed and then drawn according to different transformations without recreating the path.
The clip()
method must create a new clipping path by
calculating the intersection of the current clipping path and the area
described by the current path (after applying the current
transformation), using the non-zero winding number rule. Open
subpaths must be implicitly closed when computing the clipping path,
without affecting the actual subpaths.
When the context is created, the initial clipping path is the rectangle with the top left corner at (0,0) and the width and height of the coordinate space.
The isPointInPath(x, y)
method must return
true if the point given by the x and y coordinates passed to the method, when treated as
coordinates in the canvas' coordinate space unaffected by the current
transformation, is within the area of the canvas that is inside the
current path; and must return false otherwise.
To draw images onto the canvas, the drawImage
method can be
used.
This method is overloaded with three variants: drawImage(image, dx, dy)
, drawImage(image, dx, dy, dw, dh)
, and drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
. (Actually it is overloaded with six; each of
those three can take either an HTMLImageElement
or an HTMLCanvasElement
for the image argument.) If not specified, the dw and dh arguments default to the
values of sw and sh, interpreted
such that one CSS pixel in the image is treated as one unit in the canvas
coordinate space. If the sx, sy,
sw, and sh arguments are omitted,
they default to 0, 0, the image's intrinsic width in image pixels, and the
image's intrinsic height in image pixels, respectively.
The image argument must be an instance of an
HTMLImageElement
or HTMLCanvasElement
. If the image is of the wrong type, the implementation must raise a
TYPE_MISMATCH_ERR
exception. If one of the sy, sw, sw, and
sh arguments is outside the size of the image, or if
one of the dw and dh arguments is
negative, the implementation must raise an INDEX_SIZE_ERR
exception.
When drawImage()
is invoked, the specified region
of the image specified by the source rectangle (sx,
sy, sw, sh)
must be painted on the region of the canvas specified by the destination
rectangle (dx, dy, dw, dh).
Images are painted without affecting the current path, and are subject to transformations, shadow effects, global alpha, clipping paths, and global composition operators.
The getImageData(sx, sy, sw, sh)
method must return an ImageData
object representing the underlying
pixel data for the area of the canvas denoted by the rectangle which has
one corner at the (sx, sy)
coordinate, and that has width sw and height sh. Pixels outside the canvas must be returned as
transparent black.
ImageData
objects must be
initialised so that their height
attribute is set to
h, the number of rows in the image data, their width
attribute is
set to w, the number of physical device pixels per row
in the image data, and the data
attribute is initialised
to an array of h×w×4
integers. The pixels must be represented in this array in left-to-right
order, row by row, starting at the top left, with each pixel's red, green,
blue, and alpha components being given in that order. Each component of
each device pixel represented in this array must be in the range 0..255,
representing the 8 bit value for that component.
The putImageData(image, dx, dy)
method must take the given ImageData
structure, and draw it at the
specified location dx,dy in the
canvas coordinate space, mapping each pixel represented by the ImageData
structure into one device pixel.
The handling of pixel rounding when the specified coordinates do not exactly map to the device coordinate space is not defined by this specification, except that the following must result in no visible changes to the rendering:
context.putImageData(context.getImageData(x, y, w, h), x, y);
...for any value of x and y. In
other words, while user agents may round the arguments of the two methods
so that they map to device pixel boundaries, any rounding performed must
be performed consistently for both the getImageData()
and putImageData()
operations.
The current transformation matrix must not affect the getImageData()
and putImageData()
methods.
When a shape or image is painted, user agents must follow these steps, in the order given (or act as if they do):
globalAlpha
.