script
elementnoscript
elementtemplate
elementslot
elementcanvas
elementPath2D
objectsImageBitmap
rendering contextOffscreenCanvas
interfacecanvas
elementsScripts allow authors to add interactivity to their documents.
Authors are encouraged to use declarative alternatives to scripting where possible, as declarative mechanisms are often more maintainable, and many users disable scripting.
For example, instead of using script to show or hide a section to show more details, the
details
element could be used.
Authors are also encouraged to make their applications degrade gracefully in the absence of scripting support.
For example, if an author provides a link in a table header to dynamically resort the table, the link could also be made to function without scripts by requesting the sorted table from the server.
script
elementsrc
attribute, depends on the value of the type
attribute, but must match
script content restrictions.src
attribute, the element must be either empty or contain only
script documentation that also matches script
content restrictions.src
— Address of the resourcetype
— Type of embedded resourcenomodule
— Prevents execution in user agents that support module scriptscharset
— Character encoding of the external script resourceasync
— Execute script when available, without blockingdefer
— Defer script executioncrossorigin
— How the element handles crossorigin requestsnonce
— Cryptographic nonce used in Content Security Policy checks [CSP]integrity
— Integrity metadata used in Subresource Integrity checks [SRI][HTMLConstructor] interface HTMLScriptElement : HTMLElement { [CEReactions] attribute USVString src; [CEReactions] attribute DOMString type; [CEReactions] attribute boolean noModule; [CEReactions] attribute DOMString charset; [CEReactions] attribute boolean async; [CEReactions] attribute boolean defer; [CEReactions] attribute DOMString? crossOrigin; [CEReactions] attribute DOMString text; [CEReactions] attribute DOMString nonce; [CEReactions] attribute DOMString integrity; };
The script
element allows authors to include dynamic script and data blocks in
their documents. The element does not represent content for the
user.
The type
attribute allows customization of
the type of script represented:
Omitting the attribute, or setting it to a JavaScript MIME type, means that
the script is a classic script, to be interpreted according to the JavaScript Script top-level production. Classic scripts are affected by the
charset
, async
, and defer
attributes. Authors should omit the attribute, instead of redundantly giving a JavaScript
MIME type.
Setting the attribute to an ASCII case-insensitive match for the string
"module
" means that the script is a module script, to be
interpreted according to the JavaScript Module top-level
production. Module scripts are not affected by the charset
and defer
attributes.
Setting the attribute to any other value means that the script is a data
block, which is not processed. None of the script
attributes (except type
itself) have any effect on data blocks. Authors must use
a valid MIME type that is not a JavaScript MIME type to denote data
blocks.
The requirement that data blocks
must be denoted using a valid MIME type is in place to avoid
potential future collisions. If this specification ever adds additional types of
script, they will be triggered by setting the type
attribute to something which is not a MIME type, like how
the "module
" value denotes module
scripts. By using a valid MIME type now, you ensure that your data block will not ever be
reinterpreted as a different script type, even in future user agents.
Classic scripts and module
scripts may either be embedded inline or may be imported from an external file using the
src
attribute, which if specified gives the URL
of the external script resource to use. If src
is specified,
it must be a valid non-empty URL potentially surrounded by spaces. The contents of
inline script
elements, or the external script resource, must conform with the
requirements of the JavaScript specification's Script or Module productions, for classic
scripts and module scripts respectively. [JAVASCRIPT]
When used to include data blocks, the data must be embedded
inline, the format of the data must be given using the type
attribute, and the contents of the script
element must conform to the requirements defined for the format used. The src
, charset
, async
, nomodule
,
defer
, crossorigin
, nonce
and integrity
attributes must not be specified.
The nomodule
attribute is a boolean
attribute that prevents a script from being executed in user agents that support
module scripts. This allows selective execution of module scripts in modern user agents and classic scripts in older user agents, as shown
below. The nomodule
attribute must not be
specified on module scripts (and will be ignored if it
is).
The charset
attribute gives the character
encoding of the external script resource. The attribute must not be specified if the src
attribute is not present, or if the script is not a
classic script. (Module scripts are always
interpreted as UTF-8.) If the attribute is set, its value must be an ASCII
case-insensitive match for one of the labels of an
encoding, and must specify the same encoding as the charset
parameter of the Content-Type
metadata of the external file, if any. [ENCODING]
The async
and defer
attributes are boolean attributes that indicate how the script should be evaluated. Classic scripts may specify defer
or async
; module scripts may specify async
.
Support: script-deferChrome for Android 56+Chrome 8+UC Browser for Android 11+iOS Safari 5.0+Firefox 3.5+IE 10+Samsung Internet 4+Opera Mini NoneAndroid Browser 3+Safari 5+Edge 12+Opera 15+
Source: caniuse.com
Support: script-asyncChrome for Android 56+Chrome 8+UC Browser for Android 11+iOS Safari 5.0+Firefox 3.6+IE 10+Samsung Internet 4+Opera Mini NoneAndroid Browser 3+Safari 5.1+Edge 12+Opera 15+
Source: caniuse.com
There are several possible modes that can be selected using these attributes, and depending on the script's type.
For classic scripts, if the async
attribute is present, then the classic script will be
fetched in parallel to parsing and evaluated as soon as it is available (potentially
before parsing completes). If the async
attribute is not
present but the defer
attribute is present, then the
classic script will be fetched in parallel and evaluated when the page has finished
parsing. If neither attribute is present, then the script is fetched and evaluated immediately,
blocking parsing until these are both complete.
For module scripts, if the async
attribute is present, then the module script and all its
dependencies will be fetched in parallel to parsing, and the module script will
be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the
module script and its dependencies will be fetched in parallel to parsing and
evaluated when the page has finished parsing. (The defer
attribute has no effect on module scripts.)
This is all summarized in the following schematic diagram:
The exact processing details for these attributes are, for mostly historical
reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation
requirements are therefore by necessity scattered throughout the specification. The algorithms
below (in this section) describe the core of this processing, but these algorithms reference and
are referenced by the parsing rules for script
start and end tags in HTML, in foreign content,
and in XML, the rules for the document.write()
method, the handling of scripting, etc.
The defer
attribute may be specified even if the async
attribute is specified, to cause legacy Web browsers that
only support defer
(and not async
) to fall back to the defer
behavior instead of the blocking behavior that
is the default.
The crossorigin
attribute is a
CORS settings attribute. For classic scripts,
it controls whether error information will be exposed, when the script is obtained from other origins. For module scripts, it
controls the credentials mode used for
cross-origin requests.
Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching.
The nonce
attribute represents a cryptographic nonce ("number
used once") which can be used by Content Security Policy to determine whether or not
the script specified by an element will be executed. The value is text. [CSP]
The integrity
attribute represents the integrity metadata for requests which this
element is responsible for. The value is text. The integrity
attribute must not be specified when embedding a
module script or when the src
attribute is not
specified. [SRI]
Changing the src
, type
, charset
, nomodule
, async
, defer
, crossorigin
, nonce
and integrity
attributes dynamically has no direct
effect; these attributes are only used at specific times described below.
The IDL attributes src
, type
, charset
, defer
, integrity
, and nonce
, must each reflect the respective
content attributes of the same name.
The crossOrigin
IDL attribute must
reflect the crossorigin
content attribute.
The noModule
IDL attribute must
reflect the nomodule
content
attribute.
The async
IDL attribute controls whether the
element will execute asynchronously or not. If the element's "non-blocking" flag is
set, then, on getting, the async
IDL attribute must return
true, and on setting, the "non-blocking" flag must first be unset, and then the
content attribute must be removed if the IDL attribute's new value is false, and must be set to
the empty string if the IDL attribute's new value is true. If the element's
"non-blocking" flag is not set, the IDL attribute must reflect
the async
content attribute.
text
[ = value ]Returns the child text content of the element.
Can be set, to replace the element's children with the given value.
The IDL attribute text
must return the
child text content of the script
element. On setting, it must act the
same way as the textContent
IDL attribute.
When inserted using the document.write()
method, script
elements execute (typically blocking further script execution or HTML parsing), but when inserted using
innerHTML
and outerHTML
attributes, they do not execute at all.
In this example, two script
elements are used. One embeds an external
classic script, and the other includes some data as a data block.
<script src="game-engine.js"></script> <script type="text/x-game-map"> ........U.........e o............A....e .....A.....AAA....e .A..AAA...AAAAA...e </script>
The data in this case might be used by the script to generate the map of a video game. The data doesn't have to be used that way, though; maybe the map data is actually embedded in other parts of the page's markup, and the data block here is just used by the site's search engine to help users who are looking for particular features in their game maps.
The following sample shows how a script
element can be used to define a function
that is then used by other parts of the document, as part of a classic script. It
also shows how a script
element can be used to invoke script while the document is
being parsed, in this case to initialize the form's output.
<script> function calculate(form) { var price = 52000; if (form.elements.brakes.checked) price += 1000; if (form.elements.radio.checked) price += 2500; if (form.elements.turbo.checked) price += 5000; if (form.elements.sticker.checked) price += 250; form.elements.result.value = price; } </script> <form name="pricecalc" onsubmit="return false" onchange="calculate(this)"> <fieldset> <legend>Work out the price of your car</legend> <p>Base cost: £52000.</p> <p>Select additional options:</p> <ul> <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li> <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li> <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li> <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li> </ul> <p>Total: £<output name=result></output></p> </fieldset> <script> calculate(document.forms.pricecalc); </script> </form>
The following sample shows how a script
element can be used to include an
external module script.
<script type="module" src="app.js"></script>
This module, and all its dependencies (expressed through JavaScript import
statements in the source file), will be fetched. Once the entire
resulting module tree has been imported, and the document has finished parsing, the contents of
app.js
will be evaluated.
Additionally, if code from another script
element in the same Window
imports the module from app.js
(e.g. via import
"./app.js";
), then the same module script created by the
former script
element will be imported.
This example shows how to include a module script for modern user agents, and a classic script for older user agents:
<script type="module" src="app.js"></script> <script nomodule src="classic-app-bundle.js"></script>
In modern user agents that support module scripts, the
script
element with the nomodule
attribute
will be ignored, and the script
element with a type
of "module
" will be fetched and
evaluated (as a module script). Conversely, older user agents will ignore the
script
element with a type
of "module
", as that is an unknown script type for them — but they will have no
problem fetching and evaluating the other script
element (as a classic
script), since they do not implement the nomodule
attribute.
The following sample shows how a script
element can be used to write an inline
module script that performs a number of substitutions on the document's text, in
order to make for a more interesting reading experience (e.g. on a news site): [XKCD1288]
<script type="module"> import { walkAllTextNodeDescendants } from "./dom-utils.js"; const substitutions = new Map([ ["witnesses", "these dudes I know"] ["allegedly", "kinda probably"] ["new study", "Tumblr post"] ["rebuild", "avenge"] ["space", "spaaace"] ["Google glass", "Virtual Boy"] ["smartphone", "Pokédex"] ["electric", "atomic"] ["Senator", "Elf-Lord"] ["car", "cat"] ["election", "eating contest"] ["Congressional leaders", "river spirits"] ["homeland security", "Homestar Runner"] ["could not be reached for comment", "is guilty and everyone knows it"] ]); function substitute(textNode) { for (const [before, after] of substitutions.entries()) { textNode.data = textNode.data.replace(new RegExp(`\\b${before}\\b`, "ig"), after); } } walkAllTextNodeDescendants(document.body, substitute); </script>
Some notable features gained by using a module script include the ability to import functions
from other JavaScript modules, strict mode by default, and how top-level declarations do not
introduce new properties onto the global object. Also note that no matter where
this script
element appears in the document, it will not be evaluated until both
document parsing has complete and its dependency (dom-utils.js
) has been
fetched and evaluated.
A script
element has several associated pieces of state.
The first is a flag indicating whether or not the script block has been "already
started". Initially, script
elements must have this flag unset (script blocks,
when created, are not "already started"). The cloning
steps for script
elements must set the "already started" flag on the copy if
it is set on the element being cloned.
The second is a flag indicating whether the element was "parser-inserted". Initially,
script
elements must have this flag unset. It is set by the HTML parser
and the XML parser on script
elements they insert and affects the
processing of those elements.
The third is a flag indicating whether the element will be "non-blocking".
Initially, script
elements must have this flag set. It is unset by the HTML
parser and the XML parser on script
elements they insert. In
addition, whenever a script
element whose "non-blocking" flag is set
has an async
content attribute added, the element's
"non-blocking" flag must be unset.
The fourth is a flag indicating whether or not the script block is "ready to be
parser-executed". Initially, script
elements must have this flag unset (script
blocks, when created, are not "ready to be parser-executed"). This flag is used only for elements
that are also "parser-inserted", to let the parser know when to execute the
script.
The fifth is the script's type, which is either "classic
" or "module
". It is determined when the script is
prepared, based on the type
attribute of the element at that time.
The sixth is a flag indicating whether or not the script is from an external file. It is determined when the script is
prepared, based on the src
attribute of the element at that time.
Finally, a script
element has the script's script, which is a script
resulting from preparing the element. This is set
asynchronously after the classic script or module tree is fetched. Once it is set, either to a
script in the case of success or to null in the case of
failure, the fetching algorithms will note that the script is ready, which can trigger
other actions. The user agent must delay the load
event of the element's node document until the script is
ready.
When a script
element that is not marked as being "parser-inserted"
experiences one of the events listed in the following list, the user agent must
immediately prepare the script
element:
script
element becomes connected.script
element is connected and a node or document fragment is
inserted into the script
element, after any
script
elements inserted at that time.script
element is connected and has a src
attribute set where previously the element had no such
attribute.To prepare a script, the user agent must act as follows:
If the script
element is marked as having "already started", then
abort these steps at this point. The script is not executed.
If the element has its "parser-inserted" flag set, then set was-parser-inserted to true and unset the element's "parser-inserted" flag. Otherwise, set was-parser-inserted to false.
This is done so that if parser-inserted script
elements fail to run
when the parser tries to run them, e.g. because they are empty or specify an unsupported
scripting language, another script can later mutate them and cause them to run again.
If was-parser-inserted is true and the element does not have an async
attribute, then set the element's
"non-blocking" flag to true.
This is done so that if a parser-inserted script
element fails to
run when the parser tries to run it, but it is later executed after a script dynamically updates
it, it will execute in a non-blocking fashion even if the async
attribute isn't set.
If the element has no src
attribute, and its child
nodes, if any, consist only of comment nodes and empty Text
nodes, then abort
these steps at this point. The script is not executed.
If the element is not connected, then abort these steps. The script is not executed.
If either:
script
element has a type
attribute
and its value is the empty string, orscript
element has no type
attribute
but it has a language
attribute and that
attribute's value is the empty string, orscript
element has neither a type
attribute nor a language
attribute, then...let the script block's type string for this script
element be
"text/javascript
".
Otherwise, if the script
element has a type
attribute, let the script block's type string
for this script
element be the value of that attribute with leading and trailing ASCII whitespace
stripped.
Otherwise, the element has a non-empty language
attribute; let the script block's type string for this script
element
be the concatenation of the string "text/
" followed by the value of the
language
attribute.
The language
attribute is never
conforming, and is always ignored if there is a type
attribute present.
Determine the script's type as follows:
classic
".module
", the
script's type is "module
".If was-parser-inserted is true, then flag the element as "parser-inserted" again, and set the element's "non-blocking" flag to false.
Set the element's "already started" flag.
If the element is flagged as "parser-inserted", but the element's
node document is not the Document
of the parser that created the
element, then abort these steps.
If scripting is disabled for the script
element, then abort these steps at this point. The script is not executed.
The definition of scripting is disabled
means that, amongst others, the following scripts will not execute: scripts in
XMLHttpRequest
's responseXML
documents, scripts in DOMParser
-created documents, scripts in documents created by
XSLTProcessor
's transformToDocument
feature, and scripts
that are first inserted by a script into a Document
that was created using the
createDocument()
API. [XHR]
[DOMPARSING] [XSLTP] [DOM]
If the script
element has a nomodule
content attribute and the script's type is "classic
", then abort these steps. The script is not executed.
This means specifying nomodule
on a
module script has no effect; the algorithm continues onward.
If the script
element does not have a src
content attribute, and the Should element's inline
behavior be blocked by Content Security Policy? algorithm returns "Blocked
" when executed upon the script
element, "script
", and the script
element's child text content,
then abort these steps. The script is not executed. [CSP]
If the script
element has an event
attribute and a for
attribute, and the script's type is "classic
", then
run these substeps:
Let for be the value of the for
attribute.
Let event be the value of the event
attribute.
Strip leading and trailing ASCII whitespace from event and for.
If for is not an ASCII case-insensitive match for the
string "window
", then abort these steps at this point. The script is
not executed.
If event is not an ASCII case-insensitive match for
either the string "onload
" or the string "onload()
", then abort these steps at this point. The script is not
executed.
If the script
element has a charset
attribute, then let encoding be the result of getting an encoding from
the value of the charset
attribute.
If the script
element does not have a charset
attribute, or if getting an encoding
failed, let encoding be the same as the
encoding of the script
element's node document.
If the script's type is "module
", this encoding will be ignored.
Let CORS setting be the current state of the element's crossorigin
content attribute.
Let module script credentials mode be determined by switching on CORS setting:
omit
"same-origin
"include
"If the script
element has a nonce
attribute, then let cryptographic nonce be that attribute's value.
Otherwise, let cryptographic nonce be the empty string.
If the script
element has an integrity
attribute, then let integrity
metadata be that attribute's value.
Otherwise, let integrity metadata be the empty string.
Let parser state be "parser-inserted
" if the
script
element has been flagged as "parser-inserted", and
"not parser-inserted
" otherwise.
Let settings be the element's node document's
Window
object's environment settings object.
If the element has a src
content attribute, run these
substeps:
Let src be the value of the element's src
attribute.
If src is the empty string, queue a task to fire an event named error
at the element, and abort these steps.
Set the element's from an external file flag.
Parse src relative to the element's node document.
If the previous step failed, queue a task to fire an event named error
at the element, and abort these steps. Otherwise, let url be the resulting URL
record.
Switch on the script's type:
classic
"Fetch a classic script given url, settings, cryptographic nonce, integrity metadata, parser state, CORS setting, and encoding.
module
"Fetch a module script graph given url, settings,
"script
", cryptographic nonce, parser state,
and module script credentials mode.
When the chosen algorithm asynchronously completes, set the script's script to the result. At that time, the script is ready.
For performance reasons, user agents may start fetching the classic script or module tree
(as defined above) as soon as the src
attribute is set,
instead, in the hope that the element will be inserted into the document (and that the crossorigin
attribute won't change value in the
meantime). Either way, once the element is inserted into the document, the load must have started as described in this
step. If the UA performs such prefetching, but the element is never inserted in the document,
or the src
attribute is dynamically changed, or the crossorigin
attribute is dynamically changed, then the
user agent will not execute the script so obtained, and the fetching process will have been
effectively wasted.
If the element does not have a src
content attribute,
run these substeps:
Let source text be the value of the text
IDL attribute.
Switch on the script's type:
classic
"Let script be the result of creating a classic script using source text and settings.
Set the script's script to script.
module
"Let base URL be the script
element's node
document's document base URL.
Let script be the result of creating a module script using source text, settings, base URL, cryptographic nonce, parser state, and module script credentials mode.
If this returns null, set the script's script to null and abort these substeps; the script is ready.
Fetch the descendants of script (using an empty ancestor list). When this asynchronously completes, set the script's script to the result. At that time, the script is ready.
Then, follow the first of the following options that describes the situation:
classic
", and the element has a src
attribute, and the element has a defer
attribute, and the element has been flagged as
"parser-inserted", and the element does not have an async
attributemodule
", and
the element has been flagged as "parser-inserted", and the element does not have
an async
attributeAdd the element to the end of the list of scripts that will execute when the document
has finished parsing associated with the Document
of the parser that
created the element.
When the script is ready, set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
classic
", and the element has a src
attribute, and the element has been flagged as
"parser-inserted", and the element does not have an async
attributeThe element is the pending parsing-blocking script of the
Document
of the parser that created the element. (There can only be one such
script per Document
at a time.)
When the script is ready, set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
classic
", and the element has a src
attribute, and the element does not have an async
attribute, and the element does not have the
"non-blocking" flag setmodule
", and the element does not have an async
attribute, and the element does not have the
"non-blocking" flag setAdd the element to the end of the list of scripts that will execute in order as soon
as possible associated with the node document of the script
element at the time the prepare a script algorithm started.
When the script is ready, run the following steps:
If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.
Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.
Remove the first element from this list of scripts that will execute in order as soon as possible.
If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.
classic
", and the element has a src
attributemodule
"The element must be added to the set of scripts that will execute as soon as
possible of the node document of the script
element at the
time the prepare a script algorithm started.
When the script is ready, execute the script block and then remove the element from the set of scripts that will execute as soon as possible.
src
attribute, and the element has been flagged as
"parser-inserted", and either the parser that created the script
is
an XML parser or it's an HTML parser whose script nesting
level is not greater than one, and the Document
of the HTML
parser or XML parser that created the script
element has
a style sheet that is blocking scriptsThe element is the pending parsing-blocking script of the
Document
of the parser that created the element. (There can only be one such
script per Document
at a time.)
Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
The pending parsing-blocking script of a Document
is used by the
Document
's parser(s).
If a script
element that blocks a parser gets moved to another
Document
before it would normally have stopped blocking that parser, it nonetheless
continues blocking that parser until the condition that causes it to be blocking the parser no
longer applies (e.g. if the script is a pending parsing-blocking script because there
was a style sheet that is blocking scripts when it was parsed, but then the script is
moved to another Document
before the style sheet loads, the script still blocks the
parser until the style sheets are all loaded, at which time the script executes and the parser is
unblocked).
When the user agent is required to execute a script block, it must run the following steps.
If the element is flagged as "parser-inserted", but the element's
node document is not the Document
of the parser that created the element,
then abort these steps.
If the script's script is null, fire an event named error
at the element, and abort these steps.
If the script is from an external file, or
the script's type is "module
",
then increment the ignore-destructive-writes counter of the script
element's node document. Let neutralized doc be that
Document
.
Let old script element be the value to which the script
element's node document's currentScript
object was most recently
set.
Switch on the script's type:
classic
"If the script
element's root is not a shadow
root, then set the script
element's node document's currentScript
attribute to the
script
element. Otherwise, set it to null.
This does not use the in a document tree check, as the
script
element could have been removed from the document prior to execution,
and in that scenario currentScript
still
needs to point to it.
Run the classic script given by the script's script.
module
"Set the script
element's node document's currentScript
attribute to null.
Run the module script given by the script's script.
Set the script
element's node document's currentScript
attribute to old script
element.
Decrement the ignore-destructive-writes counter of neutralized doc, if it was incremented in the earlier step.
If the script is from an external file, then
fire an event named load
at the script
element.
A JavaScript MIME type is a MIME type string that is one of the following and refers to JavaScript: [JAVASCRIPT]
application/ecmascript
application/javascript
application/x-ecmascript
application/x-javascript
text/ecmascript
text/javascript
text/javascript1.0
text/javascript1.1
text/javascript1.2
text/javascript1.3
text/javascript1.4
text/javascript1.5
text/jscript
text/livescript
text/x-ecmascript
text/x-javascript
User agents must recognize all JavaScript MIME types.
User agents may support other MIME types for other languages, but must not support other MIME types for the languages in the list above. User agents are not required to support JavaScript. The processing model for languages other than JavaScript is outside the scope of this specification.
The following MIME types (with or without parameters) must not be interpreted as scripting languages:
These types are explicitly listed here because they are poorly-defined types that are nonetheless likely to be used as formats for data blocks, and it would be problematic if they were suddenly to be interpreted as script by a user agent.
When examining types to determine if they represent supported languages, user agents must not ignore MIME parameters. Types are to be compared including all parameters.
For example, types that include the charset
parameter will
not be recognized as referencing any of the scripting languages listed above.
script
elementsThe easiest and safest way to avoid the rather strange restrictions described in
this section is to always escape "<!--
" as "<\!--
", "<script
" as "<\script
", and "</script
" as "<\/script
" when these sequences appear in literals in scripts (e.g. in
strings, regular expressions, or comments), and to avoid writing code that uses such constructs in
expressions. Doing so avoids the pitfalls that the restrictions in this section are prone to
triggering: namely, that, for historical reasons, parsing of script
blocks in HTML is
a strange and exotic practice that acts unintuitively in the face of these sequences.
The textContent
of a script
element must match the script
production in the following ABNF, the character set for which is Unicode.
[ABNF]
script = outer *( comment-open inner comment-close outer ) outer = < any string that doesn't contain a substring that matches not-in-outer > not-in-outer = comment-open inner = < any string that doesn't contain a substring that matches not-in-inner > not-in-inner = comment-close / script-open comment-open = "<!--" comment-close = "-->" script-open = "<" s c r i p t tag-end s = %x0053 ; U+0053 LATIN CAPITAL LETTER S s =/ %x0073 ; U+0073 LATIN SMALL LETTER S c = %x0043 ; U+0043 LATIN CAPITAL LETTER C c =/ %x0063 ; U+0063 LATIN SMALL LETTER C r = %x0052 ; U+0052 LATIN CAPITAL LETTER R r =/ %x0072 ; U+0072 LATIN SMALL LETTER R i = %x0049 ; U+0049 LATIN CAPITAL LETTER I i =/ %x0069 ; U+0069 LATIN SMALL LETTER I p = %x0050 ; U+0050 LATIN CAPITAL LETTER P p =/ %x0070 ; U+0070 LATIN SMALL LETTER P t = %x0054 ; U+0054 LATIN CAPITAL LETTER T t =/ %x0074 ; U+0074 LATIN SMALL LETTER T tag-end = %x0009 ; U+0009 CHARACTER TABULATION (tab) tag-end =/ %x000A ; U+000A LINE FEED (LF) tag-end =/ %x000C ; U+000C FORM FEED (FF) tag-end =/ %x0020 ; U+0020 SPACE tag-end =/ %x002F ; U+002F SOLIDUS (/) tag-end =/ %x003E ; U+003E GREATER-THAN SIGN (>)
When a script
element contains script documentation, there are
further restrictions on the contents of the element, as described in the section below.
The following script illustrates this issue. Suppose you have a script that contains a string, as in:
var example = 'Consider this string: <!-- <script>'; console.log(example);
If one were to put this string directly in a script
block, it would violate the
restrictions above:
<script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script>
The bigger problem, though, and the reason why it would violate those restrictions, is that
actually the script would get parsed weirdly: the script block above is not terminated.
That is, what looks like a "</script>
" end tag in this snippet is
actually still part of the script
block. The script doesn't execute (since it's not
terminated); if it somehow were to execute, as it might if the markup looked as follows, it would
fail because the script (highlighted here) is not valid JavaScript:
<script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script> <!-- despite appearances, this is actually part of the script still! --> <script> ... // this is the same script block still... </script>
What is going on here is that for legacy reasons, "<!--
" and "<script
" strings in script
elements in HTML need to be balanced
in order for the parser to consider closing the block.
By escaping the problematic strings as mentioned at the top of this section, the problem is avoided entirely:
<script> var example = 'Consider this string: <\!-- <\script>'; console.log(example); </script> <!-- this is just a comment between script blocks --> <script> ... // this is a new script block </script>
It is possible for these sequences to naturally occur in script expressions, as in the following examples:
if (x<!--y) { ... } if ( player<script ) { ... }
In such cases the characters cannot be escaped, but the expressions can be rewritten so that the sequences don't occur, as in:
if (x < !--y) { ... } if (!--y > x) { ... } if (!(--y) > x) { ... } if (player < script) { ... } if (script > player) { ... }
Doing this also avoids a different pitfall as well: for related historical reasons, the string "<!--" in classic scripts is actually treated as a line comment start, just like "//".
If a script
element's src
attribute is
specified, then the contents of the script
element, if any, must be such that the
value of the text
IDL attribute, which is derived from the
element's contents, matches the documentation
production in the following
ABNF, the character set for which is Unicode. [ABNF]
documentation = *( *( space / tab / comment ) [ line-comment ] newline ) comment = slash star *( not-star / star not-slash ) 1*star slash line-comment = slash slash *not-newline ; characters tab = %x0009 ; U+0009 CHARACTER TABULATION (tab) newline = %x000A ; U+000A LINE FEED (LF) space = %x0020 ; U+0020 SPACE star = %x002A ; U+002A ASTERISK (*) slash = %x002F ; U+002F SOLIDUS (/) not-newline = %x0000-0009 / %x000B-10FFFF ; a Unicode character other than U+000A LINE FEED (LF) not-star = %x0000-0029 / %x002B-10FFFF ; a Unicode character other than U+002A ASTERISK (*) not-slash = %x0000-002E / %x0030-10FFFF ; a Unicode character other than U+002F SOLIDUS (/)
This corresponds to putting the contents of the element in JavaScript comments.
This requirement is in addition to the earlier restrictions on the syntax of
contents of script
elements.
This allows authors to include documentation, such as license information or API information,
inside their documents while still referring to external script files. The syntax is constrained
so that authors don't accidentally include what looks like valid script while also providing a
src
attribute.
<script src="cool-effects.js"> // create new instances using: // var e = new Effect(); // start the effect using .play, stop using .stop: // e.play(); // e.stop(); </script>
script
elements and XSLTThis section is non-normative.
This specification does not define how XSLT interacts with the script
element.
However, in the absence of another specification actually defining this, here are some guidelines
for implementors, based on existing implementations:
When an XSLT transformation program is triggered by an <?xml-stylesheet?>
processing instruction and the browser implements a
direct-to-DOM transformation, script
elements created by the XSLT processor need to
be marked "parser-inserted" and run in document order (modulo scripts marked defer
or async
),
immediately, as the transformation is occurring.
The XSLTProcessor.transformToDocument()
method
adds elements to a Document
that does not have a browsing context, and, accordingly, any script
elements they create need to have their "already started" flag set in the
prepare a script algorithm and never get executed (scripting is disabled). Such script
elements
still need to be marked "parser-inserted", though, such that their async
IDL attribute will return false in the absence of an async
content attribute.
The XSLTProcessor.transformToFragment()
method
needs to create a fragment that is equivalent to one built manually by creating the elements
using document.createElementNS()
. For instance,
it needs to create script
elements that aren't "parser-inserted" and
that don't have their "already started" flag set, so that they will execute when the
fragment is inserted into a document.
The main distinction between the first two cases and the last case is that the first two
operate on Document
s and the last operates on a fragment.
noscript
elementhead
element of an HTML document, if there are no ancestor noscript
elements.noscript
elements.head
element: in any order, zero or more link
elements, zero or more style
elements, and zero or more meta
elements.head
element: transparent, but there must be no noscript
element descendants.HTMLElement
.The noscript
element represents nothing if scripting is enabled, and represents its children if
scripting is disabled. It is used to present different
markup to user agents that support scripting and those that don't support scripting, by affecting
how the document is parsed.
When used in HTML documents, the allowed content model is as follows:
head
element, if scripting is
disabled for the noscript
elementThe noscript
element must contain only link
, style
,
and meta
elements.
head
element, if scripting is enabled
for the noscript
elementThe noscript
element must contain only text, except that invoking the
HTML fragment parsing algorithm with
the noscript
element as the context
element and the text contents as the input must result in a list of nodes
that consists only of link
, style
, and meta
elements that
would be conforming if they were children of the noscript
element, and no parse errors.
head
elements, if scripting is
disabled for the noscript
elementThe noscript
element's content model is transparent, with the
additional restriction that a noscript
element must not have a noscript
element as an ancestor (that is, noscript
can't be nested).
head
elements, if scripting is
enabled for the noscript
elementThe noscript
element must contain only text, except that the text must be such
that running the following algorithm results in a conforming document with no
noscript
elements and no script
elements, and such that no step in the
algorithm throws an exception or causes an HTML parser to flag a parse
error:
script
element from the document.noscript
element in the document. For every
noscript
element in that list, perform the following steps:
noscript
element.outerHTML
attribute of the
noscript
element to the value of s. (This, as a
side-effect, causes the noscript
element to be removed from the document.) [DOMPARSING]All these contortions are required because, for historical reasons, the
noscript
element is handled differently by the HTML parser based on
whether scripting was enabled or not when the parser was
invoked.
The noscript
element must not be used in XML documents.
The noscript
element is only effective in the HTML
syntax, it has no effect in the XML syntax. This is because the way it works
is by essentially "turning off" the parser when scripts are enabled, so that the contents of the
element are treated as pure text and not as real elements. XML does not define a mechanism by
which to do this.
The noscript
element has no other requirements. In particular, children of the
noscript
element are not exempt from form submission, scripting, and so
forth, even when scripting is enabled for the element.
In the following example, a noscript
element is
used to provide fallback for a script.
<form action="calcSquare.php"> <p> <label for=x>Number</label>: <input id="x" name="x" type="number"> </p> <script> var x = document.getElementById('x'); var output = document.createElement('p'); output.textContent = 'Type a number; it will be squared right then!'; x.form.appendChild(output); x.form.onsubmit = function () { return false; } x.oninput = function () { var v = x.valueAsNumber; output.textContent = v + ' squared is ' + v * v; }; </script> <noscript> <input type=submit value="Calculate Square"> </noscript> </form>
When script is disabled, a button appears to do the calculation on the server side. When script is enabled, the value is computed on-the-fly instead.
The noscript
element is a blunt instrument. Sometimes, scripts might be enabled,
but for some reason the page's script might fail. For this reason, it's generally better to avoid
using noscript
, and to instead design the script to change the page from being a
scriptless page to a scripted page on the fly, as in the next example:
<form action="calcSquare.php"> <p> <label for=x>Number</label>: <input id="x" name="x" type="number"> </p> <input id="submit" type=submit value="Calculate Square"> <script> var x = document.getElementById('x'); var output = document.createElement('p'); output.textContent = 'Type a number; it will be squared right then!'; x.form.appendChild(output); x.form.onsubmit = function () { return false; } x.oninput = function () { var v = x.valueAsNumber; output.textContent = v + ' squared is ' + v * v; }; var submit = document.getElementById('submit'); submit.parentNode.removeChild(submit); </script> </form>
The above technique is also useful in XML documents, since noscript
is not allowed there.
template
elementSupport: templateChrome for Android 56+Chrome 26+UC Browser for Android NoneiOS Safari 8+Firefox 22+IE NoneSamsung Internet 4+Opera Mini NoneAndroid Browser 4.4+Safari 7.1+Edge 13+Opera 15+
Source: caniuse.com
colgroup
element that doesn't have a span
attribute.[HTMLConstructor] interface HTMLTemplateElement : HTMLElement { readonly attribute DocumentFragment content; };
The template
element is used to declare fragments of HTML that can be cloned and
inserted in the document by script.
In a rendering, the template
element represents nothing.
The template contents of a template
element are not children of the
element itself. Instead, they are stored in a DocumentFragment
associated with a
different Document
without a browsing context so as to avoid the
template
contents interfering with the main Document
. (For example, this
avoids form controls from being submitted, scripts from executing, and so forth.) The
template contents have no conformance
requirements.
For example, consider the following document:
<!doctype html> <html lang="en"> <head> <title>Homework</title> <body> <template id="template"><p>Smile!</p></template> <script> let num = 3; const fragment = document.getElementById('template').content.cloneNode(true); while (num-- > 1) { fragment.firstChild.before(fragment.firstChild.cloneNode(true)); fragment.firstChild.textContent += fragment.lastChild.textContent; } document.body.appendChild(fragment); </script> </html>
The p
element in the template
is not a child of the
template
in the DOM; it is a child of the DocumentFragment
returned by
the template
element's content
IDL
attribute.
If the script were to call appendChild()
on the
template
element, that would add a child to the template
element (as
for any other element); however, doing so is a violation of the template
element's
content model.
content
Returns the template contents (a DocumentFragment
).
Each template
element has an associated DocumentFragment
object that
is its template contents. When a template
element is created, the user
agent must run the following steps to establish the template contents:
Let doc be the template
element's node document's appropriate template contents owner
document.
Create a DocumentFragment
object whose node document is
doc and host is the
template
element.
Set the template
element's template contents to the newly
created DocumentFragment
object.
A Document
doc's appropriate template contents owner
document is the Document
returned by the following algorithm:
If doc is not a Document
created by this algorithm, run
these substeps:
If doc does not yet have an associated inert template document then run these substeps:
Let new doc be a new Document
(that does not have a
browsing context). This is "a
Document
created by this algorithm" for the purposes of the step
above.
If doc is an HTML document, mark new doc as an HTML document also.
Let doc's associated inert template document be new doc.
Set doc to doc's associated inert template document.
Each Document
not created by this algorithm thus gets a single
Document
to act as its proxy for owning the template contents of all
its template
elements, so that they aren't in a browsing context and
thus remain inert (e.g. scripts do not run). Meanwhile, template
elements inside
Document
objects that are created by this algorithm just reuse the same
Document
owner for their contents.
Return doc.
The adopting steps
(with node and oldDocument as parameters) for template
elements
are the following:
Let doc be node's node document's appropriate template contents owner document.
node's node document is the Document
object
that node was just adopted into.
Adopt node's
template contents (a DocumentFragment
object) into doc.
The content
IDL attribute must return the
template
element's template contents.
The cloning steps for a template
element node being cloned to a copy copy must run the
following steps:
If the clone children flag is not set in the calling clone algorithm, abort these steps.
Let copied contents be the result of cloning all the children of node's template contents, with document set to copy's template contents's node document, and with the clone children flag set.
Append copied contents to copy's template contents.
In this example, a script populates a table four-column with data from a data structure, using
a template
to provide the element structure instead of manually generating the
structure from markup.
<!DOCTYPE html> <html lang='en'> <title>Cat data</title> <script> // Data is hard-coded here, but could come from the server var data = [ { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 }, { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 }, ]; </script> <table> <thead> <tr> <th>Name <th>Color <th>Sex <th>Legs <tbody> <template id="row"> <tr><td><td><td><td> </template> </table> <script> var template = document.querySelector('#row'); for (var i = 0; i < data.length; i += 1) { var cat = data[i]; var clone = template.content.cloneNode(true); var cells = clone.querySelectorAll('td'); cells[0].textContent = cat.name; cells[1].textContent = cat.color; cells[2].textContent = cat.sex; cells[3].textContent = cat.legs; template.parentNode.appendChild(clone); } </script>
This example uses cloneNode()
on the
template
's contents; it could equivalently have used document.importNode()
, which does the same thing. The
only difference between these two APIs is when the node document is updated: with
cloneNode()
it is updated when the nodes are appended
with appendChild()
, with document.importNode()
it is updated when the nodes are
cloned.
template
elements with XSLT and XPathThis section is non-normative.
This specification does not define how XSLT and XPath interact with the template
element. However, in the absence of another specification actually defining this, here are some
guidelines for implementors, which are intended to be consistent with other processing described
in this specification:
An XSLT processor based on an XML parser that acts as described
in this specification needs to act as if template
elements contain as
descendants their template contents for the purposes of the transform.
An XSLT processor that outputs a DOM needs to ensure that nodes that would go into a
template
element are instead placed into the element's template
contents.
XPath evaluation using the XPath DOM API when applied to a Document
parsed
using the HTML parser or the XML parser described in this specification
needs to ignore template contents.
slot
elementname
— Name of shadow tree slot[HTMLConstructor] interface HTMLSlotElement : HTMLElement { [CEReactions] attribute DOMString name; sequence<Node> assignedNodes(optional AssignedNodesOptions options); }; dictionary AssignedNodesOptions { boolean flatten = false; };
The slot
element defines a slot. It is
typically used in a shadow tree. A slot
element represents
its assigned nodes, if any, and its contents otherwise.
The name
content attribute may contain any
string value. It represents a slot's name.
The name
attribute is used to assign slots to other elements: a slot
element with a
name
attribute creates a named slot to which any element is assigned if that element has a slot
attribute whose
value matches that name
attribute's value, and the
slot
element is a child of the shadow tree whose root's
host has that corresponding slot
attribute value.
name
assignedNodes
()assignedNodes
({ flatten: true })slot
elements encountered therein, recursively,
until there are no slot
elements left.The name
IDL attribute must reflect
the content attribute of the same name.
The assignedNodes(options)
method, when invoked, must run these steps:
If the value of options's flatten
member is false, then
return this element's assigned nodes.
Return the result of finding flattened slotables with this element.
canvas
elementSupport: canvasChrome for Android 56+Chrome 4+UC Browser for Android 11+iOS Safari 3.2+Firefox 3.6+IE 9+Samsung Internet 4+Opera Mini (limited) all+Android Browser 3+Safari 4+Edge 12+Opera 9+
Source: caniuse.com
a
elements, img
elements with
usemap
attributes, button
elements,
input
elements whose type
attribute are in
the Checkbox or Radio Button states, input
elements that are
buttons, select
elements with a multiple
attribute or a display size greater than 1, and elements that would not be
interactive content except for having the tabindex
attribute specified.width
— Horizontal dimensionheight
— Vertical dimensiontypedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext; [HTMLConstructor] interface HTMLCanvasElement : HTMLElement { [CEReactions] attribute unsigned long width; [CEReactions] attribute unsigned long height; RenderingContext? getContext(DOMString contextId, any... arguments); USVString toDataURL(optional DOMString type, optional any quality); void toBlob(BlobCallback _callback, optional DOMString type, optional any quality); OffscreenCanvas transferControlToOffscreen(); }; callback BlobCallback = void (Blob? blob);
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 Web Components.
When authors use the canvas
element, they must also provide content that, when
presented to the user, conveys essentially the same function or purpose as the
canvas
's bitmap. This content may be placed as content of the canvas
element. The contents of the canvas
element, if any, are the element's fallback
content.
In interactive visual media, if scripting is enabled for
the canvas
element, and if support for canvas
elements has been enabled,
then the canvas
element represents embedded content
consisting of a dynamically created image, the element's bitmap.
In non-interactive, static, visual media, if the canvas
element has been
previously associated with a rendering context (e.g. if the page was viewed in an interactive
visual medium and is now being printed, or if some script that ran during the page layout process
painted on the element), then the canvas
element represents
embedded content with the element's current bitmap and size. Otherwise, the element
represents its fallback content instead.
In non-visual media, and in visual media if scripting is
disabled for the canvas
element or if support for canvas
elements
has been disabled, the canvas
element represents its fallback
content instead.
When a canvas
element represents embedded content, the
user can still focus descendants of the canvas
element (in the fallback
content). When an element is focused, it is the target of keyboard interaction
events (even though the element itself is not visible). This allows authors to make an interactive
canvas keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable areas in the fallback content. (Focus has no
effect on mouse interaction events.) [UIEVENTS]
An element whose nearest canvas
element ancestor is being rendered
and represents embedded content is an element that is being used as
relevant canvas fallback content.
The canvas
element has two attributes to control the size of the element's bitmap:
width
and height
. These attributes, when specified, must have
values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their
numeric values. If an attribute is missing, or if parsing its value returns an error, then the
default value must be used instead. 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.
The user agent must use a square pixel density consisting of one pixel of image data per
coordinate space unit for the bitmaps of a canvas
and its rendering contexts.
A canvas
element can be sized arbitrarily by a style sheet, its
bitmap is then subject to the 'object-fit' CSS property.
The bitmaps of canvas
elements, the bitmaps of ImageBitmap
objects,
as well as some of the bitmaps of rendering contexts, such as those described in the sections on
the CanvasRenderingContext2D
and ImageBitmapRenderingContext
objects
below, have an origin-clean flag, which can be
set to true or false. Initially, when the canvas
element or ImageBitmap
object is created, its bitmap's origin-clean
flag must be set to true.
A canvas
element can have a rendering context bound to it. Initially, it does not
have a bound rendering context. To keep track of whether it has a rendering context or not, and
what kind of rendering context it is, a canvas
also has a canvas context mode, which is initially none but can be changed to either placeholder, 2d, bitmaprenderer, or webgl by algorithms defined in this specification.
When its canvas context mode is none, a canvas
element has no rendering context,
and its bitmap must be fully transparent black with an intrinsic width equal to the
numeric value of the element's width
attribute and an
intrinsic height equal to the numeric value of the element's height
attribute, those values being interpreted in CSS pixels, and being updated as the attributes are set, changed, or
removed.
When its canvas context mode is placeholder, a canvas
element has no
rendering context. It serves as a placeholder for an OffscreenCanvas
object, and
the content of the canvas
element is updated by calling the commit()
method of the OffscreenCanvas
object's rendering context.
When a canvas
element represents embedded content, it provides a
paint source whose width is the element's intrinsic width, whose height
is the element's intrinsic height, and whose appearance is the element's bitmap.
Whenever the width
and height
content attributes are set, removed, changed, or
redundantly set to the value they already have, then the user agent must perform the action
from the row of the following table that corresponds to the canvas
element's context mode.
Action | |
---|---|
Follow the steps to set bitmap
dimensions to the numeric values of the | |
Follow the behavior defined in the WebGL specification. [WEBGL] | |
If the context's bitmap
mode is set to blank,
run the steps to set an | |
Do nothing. | |
Do nothing. |
The width
and height
IDL attributes must reflect the
respective content attributes of the same name, with the same defaults.
getContext
(contextId [, ... ] )Returns an object that exposes an API for drawing on the canvas. The first argument
specifies the desired API, either "2d
", "bitmaprenderer
" or "webgl
". Subsequent arguments are handled by that API.
This specification defines the "2d
" and "bitmaprenderer
" contexts below. There is also a
specification that defines a "webgl
" context.
[WEBGL]
Returns null if the given context ID is not supported, or if the canvas has already been
initialized with another context type (e.g. trying to get a "2d
" context after getting a "webgl
" context).
The getContext(contextId,
arguments...)
method of the canvas
element, when invoked,
must run the steps in the cell of the following table whose column header describes the
canvas
element's canvas context
mode and whose row header describes the method's first argument.
none | 2d | bitmaprenderer | webgl | placeholder | |
---|---|---|---|---|---|
"2d "
|
Follow the 2D context creation algorithm defined in the section below, passing
it the canvas element and the method's arguments..., to obtain a
CanvasRenderingContext2D object; if this does not throw an exception, then
set the canvas element's context
mode to 2d, and return the
CanvasRenderingContext2D object.
| Return the same object as was returned the last time the method was invoked with this same first argument. | Return null. | Return null. |
Throw an "InvalidStateError " DOMException .
|
"bitmaprenderer "
|
Follow the ImageBitmapRenderingContext creation algorithm defined
in the section below, passing it the canvas element and the method's
arguments..., to obtain an ImageBitmapRenderingContext object; then
set the canvas element's context
mode to bitmaprenderer, and return the
ImageBitmapRenderingContext object.
| Return null. | Return the same object as was returned the last time the method was invoked with this same first argument. | Return null. |
Throw an "InvalidStateError " DOMException .
|
"webgl ", if the user agent supports the WebGL feature in its current configuration
|
Follow the instructions given in the WebGL specification's Context Creation section to
obtain either a WebGLRenderingContext or null; if the returned value is null,
then return null and abort these steps, otherwise, set the canvas element's
context mode to webgl, and return the WebGLRenderingContext
object [WEBGL]
| Return null. | Return null. | Return the same object as was returned the last time the method was invoked with this same first argument. |
Throw an "InvalidStateError " DOMException .
|
An unsupported value* | Return null. | Return null. | Return null. | Return null. |
Throw an "InvalidStateError " DOMException .
|
* For example, the "webgl
"
value in the case of a user agent having exhausted the graphics hardware's abilities and having no
software fallback implementation.
toDataURL
( [ type [, quality ] ] )Returns a data:
URL for the image in the
canvas.
The first argument, if provided, controls the type of the image to be returned (e.g. PNG or
JPEG). The default is "image/png
"; that type is also used if the given type isn't
supported. The second argument applies if the type is an image format that supports variable
quality (such as "image/jpeg
"), and is a number in the range 0.0 to 1.0 inclusive
indicating the desired quality level for the resulting image.
When trying to use types other than "image/png
", authors can check if the image
was really returned in the requested format by checking to see if the returned string starts
with one of the exact strings "data:image/png,
" or "data:image/png;
". If it does, the image is PNG, and thus the requested type was
not supported. (The one exception to this is if the canvas has either no height or no width, in
which case the result might simply be "data:,
".)
toBlob
(callback [, type [, quality ] ] )Creates a Blob
object representing a file containing the image in the canvas,
and invokes a callback with a handle to that object.
The second argument, if provided, controls the type of the image to be returned (e.g. PNG or
JPEG). The default is "image/png
"; that type is also used if the given type isn't
supported. The third argument applies if the type is an image format that supports variable
quality (such as "image/jpeg
"), and is a number in the range 0.0 to 1.0 inclusive
indicating the desired quality level for the resulting image.
transferControlToOffscreen
()Returns a newly created OffscreenCanvas
object that uses the
canvas
element as a placeholder. Once the canvas
element has become a
placeholder for an OffscreenCanvas
object, its intrinsic size can no longer be
changed, and it cannot have a rendering context. The content of the placeholder canvas is
updated by calling the commit()
method of the
OffscreenCanvas
object's rendering context.
The toDataURL(type,
quality)
method, when invoked, must run these steps:
If this canvas
element's bitmap's origin-clean flag is set to false, then throw a
"SecurityError
" DOMException
and abort these steps.
If this canvas
element's bitmap has no pixels (i.e. either its horizontal
dimension or its vertical dimension is zero) then return the string "data:,
" and abort these steps. (This is the shortest data:
URL; it represents the empty string in a text/plain
resource.)
Let file be a
serialization of this canvas
element's bitmap as a file, passing
type and quality if they were given.
If file is null then return "data:,
".
The toBlob(callback, type,
quality)
method, when invoked, must run these steps:
If this canvas
element's bitmap's origin-clean flag is set to false, then throw a
"SecurityError
" DOMException
and abort these steps.
If this canvas
element's bitmap has no pixels (i.e. either its horizontal
dimension or its vertical dimension is zero) then let result be null.
Otherwise, let result be a Blob
object representing a serialization of this canvas
element's
bitmap as a file, passing type and quality if they were given. [FILEAPI]
Return, but continue running these steps in parallel.
Queue a task to invoke
the BlobCallback
callback with result as its argument. The
task source for this task is the
canvas blob serialization task
source.
The transferControlToOffscreen()
method,
when invoked, must run these steps:
If this canvas
element's context
mode is not set to none, throw an
"InvalidStateError
" DOMException
and abort these
steps.
Let offscreenCanvas be a new OffscreenCanvas
object with its
width and height equal to the values of the width
and height
content attributes of this
canvas
element.
Set the placeholder canvas
element of offscreenCanvas to be a weak reference to this canvas
element.
Set this canvas
element's context
mode to placeholder.
Return offscreenCanvas.
Spec bugs: 18220
typedef (HTMLImageElement or SVGImageElement) HTMLOrSVGImageElement; typedef (HTMLOrSVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas) CanvasImageSource; enum CanvasFillRule { "nonzero", "evenodd" }; dictionary CanvasRenderingContext2DSettings { boolean alpha = true; }; enum ImageSmoothingQuality { "low", "medium", "high" }; interface CanvasRenderingContext2D { // back-reference to the canvas readonly attribute HTMLCanvasElement canvas; }; CanvasRenderingContext2D implements CanvasState; CanvasRenderingContext2D implements CanvasTransform; CanvasRenderingContext2D implements CanvasCompositing; CanvasRenderingContext2D implements CanvasImageSmoothing; CanvasRenderingContext2D implements CanvasFillStrokeStyles; CanvasRenderingContext2D implements CanvasShadowStyles; CanvasRenderingContext2D implements CanvasFilters; CanvasRenderingContext2D implements CanvasRect; CanvasRenderingContext2D implements CanvasDrawPath; CanvasRenderingContext2D implements CanvasUserInterface; CanvasRenderingContext2D implements CanvasText; CanvasRenderingContext2D implements CanvasDrawImage; CanvasRenderingContext2D implements CanvasImageData; CanvasRenderingContext2D implements CanvasPathDrawingStyles; CanvasRenderingContext2D implements CanvasTextDrawingStyles; CanvasRenderingContext2D implements CanvasPath; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasState { // state void save(); // push state on state stack void restore(); // pop state stack and restore state }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasTransform { // transformations (default transform is the identity matrix) 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); [NewObject] DOMMatrix getTransform(); void setTransform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f); void setTransform(optional DOMMatrixInit transform); void resetTransform(); }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasCompositing { // compositing attribute unrestricted double globalAlpha; // (default 1.0) attribute DOMString globalCompositeOperation; // (default source-over) }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasImageSmoothing { // image smoothing attribute boolean imageSmoothingEnabled; // (default true) attribute ImageSmoothingQuality imageSmoothingQuality; // (default low) }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasFillStrokeStyles { // colors and styles (see also the CanvasPathDrawingStyles and CanvasTextDrawingStyles interfaces) 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, [TreatNullAs=EmptyString] DOMString repetition); }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasShadowStyles { // 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) }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasFilters { // filters attribute DOMString filter; // (default "none") }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasRect { // 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); }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasDrawPath { // path API (see also CanvasPath) void beginPath(); void fill(optional CanvasFillRule fillRule = "nonzero"); void fill(Path2D path, optional CanvasFillRule fillRule = "nonzero"); void stroke(); void stroke(Path2D path); void clip(optional CanvasFillRule fillRule = "nonzero"); void clip(Path2D path, optional CanvasFillRule fillRule = "nonzero"); void resetClip(); boolean isPointInPath(unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero"); boolean isPointInPath(Path2D path, unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero"); boolean isPointInStroke(unrestricted double x, unrestricted double y); boolean isPointInStroke(Path2D path, unrestricted double x, unrestricted double y); }; [NoInterfaceObject] interface CanvasUserInterface { void drawFocusIfNeeded(Element element); void drawFocusIfNeeded(Path2D path, Element element); void scrollPathIntoView(); void scrollPathIntoView(Path2D path); }; [NoInterfaceObject] interface CanvasText { // text (see also the CanvasPathDrawingStyles and CanvasTextDrawingStyles interfaces) 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); }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasDrawImage { // 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); }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasImageData { // pixel manipulation ImageData createImageData(double sw, double sh); ImageData createImageData(ImageData imagedata); ImageData getImageData(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); }; enum CanvasLineCap { "butt", "round", "square" }; enum CanvasLineJoin { "round", "bevel", "miter" }; enum CanvasTextAlign { "start", "end", "left", "right", "center" }; enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" }; enum CanvasDirection { "ltr", "rtl", "inherit" }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasPathDrawingStyles { // line caps/joins attribute unrestricted double lineWidth; // (default 1) attribute CanvasLineCap lineCap; // (default "butt") attribute CanvasLineJoin lineJoin; // (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; }; [NoInterfaceObject] interface CanvasTextDrawingStyles { // text attribute DOMString font; // (default 10px sans-serif) attribute CanvasTextAlign textAlign; // (default: "start") attribute CanvasTextBaseline textBaseline; // (default: "alphabetic") attribute CanvasDirection direction; // (default: "inherit") }; [NoInterfaceObject, Exposed=(Window,Worker)] interface CanvasPath { // 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, optional boolean anticlockwise = false); }; [Exposed=(Window,Worker)] interface CanvasGradient { // opaque object void addColorStop(double offset, DOMString color); }; [Exposed=(Window,Worker)] interface CanvasPattern { // opaque object void setTransform(optional DOMMatrixInit 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; }; [Constructor(unsigned long sw, unsigned long sh), Constructor(Uint8ClampedArray data, unsigned long sw, optional unsigned long sh), Exposed=(Window,Worker)] interface ImageData { readonly attribute unsigned long width; readonly attribute unsigned long height; readonly attribute Uint8ClampedArray data; }; [Constructor, Constructor(Path2D path), Constructor(sequence<Path2D> paths, optional CanvasFillRule fillRule = "nonzero"), Constructor(DOMString d), Exposed=(Window,Worker)] interface Path2D { void addPath(Path2D path, optional DOMMatrixInit transform); }; Path2D implements CanvasPath;
To maintain compatibility with existing Web content, user agents need to enumerate
methods defined in CanvasUserInterface
immediately after the stroke(Path2D)
method on CanvasRenderingContext2D
objects.
getContext
('2d' [, { [ alpha
: false ] } ] )Returns a CanvasRenderingContext2D
object that is permanently bound to a
particular canvas
element.
If the alpha
setting is
provided and set to false, then the canvas is forced to always be opaque.
canvas
Returns the canvas
element.
A CanvasRenderingContext2D
object has an output bitmap that
is initialized when the object is created.
The output bitmap has an origin-clean flag, which can be set to true or false. Initially, when one of these bitmaps is created, its origin-clean flag must be set to true.
The CanvasRenderingContext2D
object also has an alpha flag, which can be set to true or false. Initially,
when the context is created, its alpha flag must be
set to true. When a CanvasRenderingContext2D
object has its alpha flag set to false, then its alpha channel must be
fixed to 1.0 (fully opaque) for all pixels, and attempts to change the alpha component of any
pixel must be silently ignored.
Thus, the bitmap of such a context starts off as fully-opaque black instead of
fully-transparent black; clearRect()
always
results in fully-opaque black pixels, every fourth byte from getImageData()
is always 255, the putImageData()
method effectively ignores every
fourth byte in its input, and so on. However, the alpha component of styles and images drawn
onto the canvas are still honoured up to the point where they would impact the output
bitmap's alpha channel; for instance, drawing a 50% transparent white square on a freshly
created output bitmap with its alpha
flag set to false will result in a fully-opaque gray square.
The CanvasRenderingContext2D
2D rendering context represents a flat linear
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. The x-coordinate of the right-most edge is equal to the width of the rendering
context's output bitmap in CSS pixels; similarly, the
y-coordinate of the bottom-most edge is equal to the height of the rendering context's
output bitmap in CSS pixels.
The size of the coordinate space does not necessarily represent the size of the actual bitmaps that the user agent will use internally or during rendering. On high-definition displays, for instance, the user agent may internally use bitmaps with two device pixels per unit in the coordinate space, so that the rendering remains at high quality throughout. Anti-aliasing can similarly be implemented using over-sampling with bitmaps of a higher resolution than the final image on the display.
The 2D context creation algorithm, which is passed a target (a
canvas
element) and optionally some arguments, consists of running the following
steps:
If the algorithm was passed some arguments, then let arg be the first such argument. Otherwise, let arg be undefined.
Let settings be the result of coercing the arg context arguments for 2D.
Create a new CanvasRenderingContext2D
object.
Initialize its canvas
attribute to point to
target.
Let the new CanvasRenderingContext2D
object's output bitmap be
the same bitmap as target's bitmap (so that they are shared).
Set bitmap dimensions to the
numeric values of target's width
and
height
content attributes.
Process each of the members of settings as follows:
alpha
CanvasRenderingContext2D
object's alpha flag to false.Return the new CanvasRenderingContext2D
object.
When a user agent is required to coerce context arguments for 2D, it must run these steps:
Let input be the argument to coerce.
Let jsval be the result of converting input to a JavaScript value. If this throws an exception, then propagate the exception and abort these steps.
Let dict be the result of converting
jsval to the dictionary type CanvasRenderingContext2DSettings
. If this
throws an exception, then propagate the exception and abort these steps.
Return dict.
When the user agent is to set bitmap dimensions to width and height, it must run these steps:
Resize the output bitmap to the new width and height and clear it to fully transparent black.
Let canvas be the canvas
element to which the rendering
context's canvas
attribute was initialized.
If the numeric value of canvas's width
content attribute differs from width, then set canvas's width
content attribute to the shortest possible string
representing width as a valid non-negative integer.
If the numeric value of canvas's height
content attribute differs from height, then set canvas's height
content attribute to the shortest possible string
representing height as a valid non-negative integer.
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 user agent is to run the unbinding steps for a rendering context, it must run these steps:
Clear the CanvasRenderingContext2D
object's output bitmap to a
transparent black.
Set the CanvasRenderingContext2D
object's origin-clean flag to true.
Let the CanvasRenderingContext2D
object have no output
bitmap.
When the user agent is to run the binding
steps to bind the rendering context to the canvas
element target, it
must run these steps:
Resize the CanvasRenderingContext2D
object's output bitmap to
the dimensions of target's bitmap and clear it to fully transparent black.
Set the CanvasRenderingContext2D
object's origin-clean flag to true.
Let the CanvasRenderingContext2D
object's output bitmap be target's bitmap.
The canvas
attribute must return the
value it was initialized to when the object was created.
Whenever the CSS value currentColor
is used as a color in the CanvasRenderingContext2D
API, the computed value of the currentColor
keyword is
the computed value of the 'color' property on the canvas
element at the time that the color is specified (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. [CSSCOLOR]
In the case of addColorStop()
on
CanvasGradient
, the "computed value of the 'color'
property" for the purposes of determining the computed value of the currentColor
keyword is always fully opaque black (there is no associated
element). [CSSCOLOR]
This is because CanvasGradient
objects are
canvas
-neutral — a CanvasGradient
object created by one
canvas
can be used by another, and there is therefore no way to know which is the
"element in question" at the time that the color is specified.
Similar concerns exist with font-related properties; the rules for those are described in detail in the relevant section below.
The CanvasFillRule
enumeration is used to select the fill rule
algorithm by which to determine if a point is inside or outside a path.
The value "nonzero
" value
indicates the non-zero winding rule, wherein
a point is considered to be outside a shape if the number of times a half-infinite straight
line drawn from that point crosses the shape's path going in one direction is equal to the
number of times it crosses the path going in the other direction.
The "evenodd
" value indicates
the even-odd rule, wherein
a point is considered to be outside a shape if the number of times a half-infinite straight
line drawn from that point crosses the shape's path is even.
If a point is not outside a shape, it is inside the shape.
The ImageSmoothingQuality
enumeration is used to express a preference for the
interpolation quality to use when smoothing images.
The "low
" value
indicates a preference for a low level of image interpolation quality. Low-quality image
interpolation may be more computationally efficient than higher settings.
The "medium
" value
indicates a preference for a medium level of image interpolation quality.
The "high
" value
indicates a preference for a high level of image interpolation quality. High-quality image
interpolation may be more computationally expensive than lower settings.
Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-smoothing algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used.
This section is non-normative.
The output bitmap, when it is not directly displayed by the user agent,
implementations can, instead of updating this bitmap, merely remember the sequence of drawing
operations that have been applied to it until such time as the bitmap's actual data is needed
(for example because of a call to drawImage()
, or
the createImageBitmap()
factory method). In many
cases, this will be more memory efficient.
The bitmap of a canvas
element is the one bitmap that's pretty much always going
to be needed in practice. The output bitmap of a rendering context, when it has one,
is always just an alias to a canvas
element's bitmap.
Additional bitmaps are sometimes needed, e.g. to enable fast drawing when the canvas is being painted at a different size than its intrinsic size, or to enable double buffering so that graphics updates, like page scrolling for example, can be processed concurrently while canvas draw commands are being executed.
Objects that implement the CanvasState
interface maintain a stack of drawing
states. Drawing states consist of:
strokeStyle
, fillStyle
, globalAlpha
, lineWidth
, lineCap
, lineJoin
, miterLimit
, lineDashOffset
, shadowOffsetX
, shadowOffsetY
, shadowBlur
, shadowColor
, filter
, globalCompositeOperation
, font
, textAlign
, textBaseline
, direction
, imageSmoothingEnabled
, imageSmoothingQuality
.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.
save
()Pushes the current state onto the stack.
restore
()Pops the top state on the stack, restoring the context to that state.
The save()
method, when invoked, must push
a copy of the current drawing state onto the drawing state stack.
The restore()
method, when invoked,
must pop the top entry in the drawing state stack, and reset the drawing state it describes. If
there is no saved state, then the method must do nothing.
When the user agent is to reset the rendering context to its default state, it must clear the drawing state stack and everything that drawing state consists of to initial values.
lineWidth
[ = value ]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.
lineCap
[ = value ]lineCap
[ = value ]Returns the current line cap style.
Can be set, to change the line cap style.
The possible line cap styles are "butt
", "round
", and "square
". Other values are ignored.
lineJoin
[ = value ]lineJoin
[ = value ]Returns the current line join style.
Can be set, to change the line join style.
The possible line join styles are "bevel
", "round
", and "miter
". Other values are ignored.
miterLimit
[ = value ]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.
setLineDash
(segments)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.
getLineDash
()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).
lineDashOffset
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.
Objects that implement the CanvasPathDrawingStyles
interface have attributes and
methods (defined in this section) that control how lines are treated by the object.
The lineWidth
attribute gives the
width of lines, in coordinate space units. On getting, it must return the current value. On
setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged;
other values must change the current value to the new value.
When the object implementing the CanvasPathDrawingStyles
interface is created, the
lineWidth
attribute must initially have the value
1.0.
The lineCap
attribute defines the type
of endings that UAs will place on the end of lines. The three valid values are "butt
", "round
", and "square
".
On getting, it must return the current value. On setting, the current value must be changed to the new value.
When the object implementing the CanvasPathDrawingStyles
interface is created, the
lineCap
attribute must initially have the value
"butt
".
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 getting, it must return the current value. On setting, the current value must be changed to the new value.
When the object implementing the CanvasPathDrawingStyles
interface is created, the
lineJoin
attribute must initially have the value
"miter
".
When the lineJoin
attribute has the value "miter
", strokes use the miter limit ratio to decide how to render joins. The
miter limit ratio can be explicitly set using the miterLimit
attribute. On getting, it must return
the current value. On setting, zero, negative, infinite, and NaN values must be ignored, leaving
the value unchanged; other values must change the current value to the new value.
When the object implementing the CanvasPathDrawingStyles
interface is created, the
miterLimit
attribute must initially have the value
10.0.
Each CanvasPathDrawingStyles
object has a dash list, which is either
empty or consists of an even number of non-negative numbers. Initially, the dash list
must be empty.
The setLineDash()
method, when
invoked, must run these steps:
Let a be the argument.
If any value in a is not finite (e.g. an Infinity or a NaN value), or if any value is negative (less than zero), then abort these steps (without throwing an exception; user agents could show a message on a developer console, though, as that would be helpful for debugging).
If the number of elements in a is odd, then let a be the concatenation of two copies of a.
Let the object's dash list be a.
When the getLineDash()
method is
invoked, it must return a sequence whose values are the values of the object's dash
list, in the same order.
It is sometimes useful to change the "phase" of the dash pattern, e.g. to achieve a "marching
ants" effect. The phase can be set using the lineDashOffset
attribute. On getting, it must
return the current value. On setting, infinite and NaN values must be ignored, leaving the value
unchanged; other values must change the current value to the new value.
When the object implementing the CanvasPathDrawingStyles
interface is created, the
lineDashOffset
attribute must initially have
the value 0.0.
When a user agent is to trace a path, given an object style
that implements the CanvasPathDrawingStyles
interface, it must run the following
algorithm. This algorithm returns a new path.
Let path be a copy of the path being traced.
Prune all zero-length line segments from path.
Remove from path any subpaths containing no lines (i.e. subpaths with just one point).
Replace each point in each subpath of path other than the first point and the last point of each subpath by a join that joins the line leading to that point to the line leading out of that point, such that the subpaths all consist of two points (a starting point with a line leading out of it, and an ending point with a line leading into it), one or more lines (connecting the points and the joins), and zero or more joins (each connecting one line to another), connected together such that each subpath is a series of one or more lines with a join between each one and a point on each end.
Add a straight closing line to each closed subpath in path connecting the last point and the first point of that subpath; change the last point to a join (from the previously last line to the newly added closing line), and change the first point to a join (from the newly added closing line to the first line).
If the styles dash list is empty, then jump to the step labeled convert.
Let pattern width be the concatenation of all the entries of the styles dash list, in coordinate space units.
For each subpath subpath in path, run the following substeps. These substeps mutate the subpaths in path in vivo.
Let subpath width be the length of all the lines of subpath, in coordinate space units.
Let offset be the value of the styles lineDashOffset
, in coordinate space
units.
While offset is greater than pattern width, decrement it by pattern width.
While offset is less than zero, increment it by pattern width.
Define L to be a linear coordinate line defined along all lines in subpath, such that the start of the first line in the subpath is defined as coordinate 0, and the end of the last line in the subpath is defined as coordinate subpath width.
Let position be zero minus offset.
Let index be 0.
Let current state be off (the other states being on and zero-on).
Dash on: Let segment length be the value of the styles dash list's indexth entry.
Increment position by segment length.
If position is greater than subpath width, then end these substeps for this subpath and start them again for the next subpath; if there are no more subpaths, then jump to the step labeled convert instead.
If segment length is non-zero, then let current state be on.
Increment index by one.
Dash off: Let segment length be the value of the styles dash list's indexth entry.
Let start be the offset position on L.
Increment position by segment length.
If position is less than zero, then jump to the step labeled post-cut.
If start is less than zero, then let start be zero.
If position is greater than subpath width, then let end be the offset subpath width on L. Otherwise, let end be the offset position on L.
Jump to the first appropriate step:
Do nothing, just continue to the next step.
Cut the line on which end finds itself short at end and place a point there, cutting the subpath that it was in in two; remove all line segments, joins, points, and subpaths that are between start and end; and finally place a single point at start with no lines connecting to it.
The point has a directionality for the purposes of drawing line caps (see below). The directionality is the direction that the original line had at that point (i.e. when L was defined above).
Cut the line on which start finds itself into two at start and place a point there, cutting the subpath that it was in in two, and similarly cut the line on which end finds itself short at end and place a point there, cutting the subpath that it was in in two, and then remove all line segments, joins, points, and subpaths that are between start and end.
If start and end are the same point, then this results in just the line being cut in two and two points being inserted there, with nothing being removed, unless a join also happens to be at that point, in which case the join must be removed.
Post-cut: If position is greater than subpath width, then jump to the step labeled convert.
If segment length is greater than zero, then let positioned-at-on-dash be false.
Increment index by one. If it is equal to the number of entries in the styles dash list, then let index be 0.
Return to the step labeled dash on.
Convert: This is the step that converts the path to a new path that represents its stroke.
Create a new path that describes the edge of the areas
that would be covered if a straight line of length equal to the styles
lineWidth
was swept along each subpath in path while being kept at an angle such that the line is orthogonal to the path
being swept, replacing each point with the end cap necessary to satisfy the styles lineCap
attribute as
described previously and elaborated below, and replacing each join with the join necessary to
satisfy the styles lineJoin
type, as defined below.
Caps: Each point has a flat edge perpendicular to the direction of the line
coming out of it. This is them augmented according to the value of the styles lineCap
. The "butt
" value means that no additional line cap is added. The "round
" value means that a semi-circle with the diameter equal to the styles lineWidth
width must
additionally be placed on to the line coming out of each point. The "square
" value means that a rectangle with the length of the styles lineWidth
width and the
width of half the styles lineWidth
width, placed flat against the edge
perpendicular to the direction of the line coming out of the point, must be added at each
point.
Points with no lines coming out of them must have two caps placed back-to-back as if it was really two points connected to each other by an infinitesimally short straight line in the direction of the point's directionality (as defined above).
Joins: In addition to the point where a 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 triangle connecting these two opposite corners with a straight line, with the third point
of the triangle being the join point, must be added at all joins. 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.
The "round
" value means that an 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 added at
joins.
The "miter
" value means that a second triangle must (if it can given
the miter length) be added 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.
The miter length is the distance from the point where the join occurs 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
(as set by the style miterLimit
attribute) to be exceeded, then this second
triangle must not be added.
The subpaths in the newly created path must be oriented such that for any point, the number of times a half-infinite straight line drawn from that point crosses a subpath is even if and only if the number of times a half-infinite straight line drawn from that same point crosses a subpath going in one direction is equal to the number of times it crosses a subpath going in the other direction.
Return the newly created path.
font
[ = value ]font
[ = value ]Returns the current font settings.
Can be set, to change the font. The syntax is the same as for the CSS 'font' property; values that cannot be parsed as CSS font values are ignored.
Relative keywords and lengths are computed relative to the font of the canvas
element.
textAlign
[ = value ]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
".
textBaseline
[ = value ]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
".
direction
[ = value ]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
".
Objects that implement the CanvasTextDrawingStyles
interface have attributes
(defined in this section) that control how text is laid out (rasterized or outlined) by the
object. Such objects can also have a font style source object. For
CanvasRenderingContext2D
objects, this is the canvas
element
referenced by the context's canvas property.
The font
IDL attribute, on setting, must
be parsed as a CSS <'font'>
value (but without supporting property-independent style sheet syntax like 'inherit'), and
the resulting font must be assigned to the context, with the 'line-height' component
forced to 'normal', with the 'font-size' component converted to CSS pixels, and with system fonts being computed to explicit values. If the
new value is syntactically incorrect (including using property-independent style sheet syntax like
'inherit' or 'initial'), then it must be ignored, without assigning a new font value. [CSS]
Font family names must be interpreted in the context of the font style source
object when the font is to be used; any fonts embedded using @font-face
or loaded using FontFace
objects that are visible to the
font style source object must therefore be available once they are loaded. (Each font style source
object has a font source, which determines what fonts are available.) If a font
is used before it is fully loaded, or if the font style source object does not have
that font in scope at the time the font is to be used, then it must be treated as if it was an
unknown font, falling back to another as described by the relevant CSS specifications. [CSSFONTS] [CSSFONTLOAD]
On getting, the font
attribute must return the serialized form of the current font of the context (with
no 'line-height' component). [CSSOM]
For example, after the following statement:
context.font = 'italic 400 12px/2 Unknown Font, sans-serif';
...the expression context.font
would evaluate to the string "italic 12px "Unknown Font", sans-serif
". The "400"
font-weight doesn't appear because that is the default value. The line-height doesn't appear
because it is forced to "normal", the default value.
When the object implementing the CanvasTextDrawingStyles
interface is created, the
font of the context must be set to 10px sans-serif. When the 'font-size' component is
set to lengths using percentages, 'em' or 'ex' units, or the 'larger' or
'smaller' keywords, these must be interpreted relative to the computed value of the
'font-size' property of the font style source object at the time that
the attribute is set, if it is an element. When the 'font-weight' component is set to
the relative values 'bolder' and 'lighter', these must be interpreted relative to the
computed value of the 'font-weight' property of the font style
source object at the time that the attribute is set, if it is an element. If the computed values are undefined for a particular case (e.g. because
the font style source object is not an element or is not being
rendered), then the relative keywords must be interpreted relative to the normal-weight
10px sans-serif default.
The textAlign
IDL attribute, on
getting, must return the current value. On setting, the current value must be changed to the new
value. When the object implementing the CanvasTextDrawingStyles
interface is
created, the textAlign
attribute must initially
have the value start
.
The textBaseline
IDL attribute, on
getting, must return the current value. On setting, the current value must be changed to the new
value. When the object implementing the CanvasTextDrawingStyles
interface is
created, the textBaseline
attribute must
initially have the value alphabetic
.
The direction
IDL attribute, on
getting, must return the current value. On setting, the current value must be changed to the new
value. When the object implementing the CanvasTextDrawingStyles
interface is
created, the direction
attribute must initially
have the value "inherit
".
The textAlign
attribute's allowed keywords are
as follows:
start
Align to the start edge of the text (left side in left-to-right text, right side in right-to-left text).
end
Align to the end edge of the text (right side in left-to-right text, left side in right-to-left text).
left
Align to the left.
right
Align to the right.
center
Align to the center.
The textBaseline
attribute's allowed keywords correspond to alignment points in the
font:
The keywords map to these alignment points as follows:
top
hanging
middle
alphabetic
ideographic
bottom
The direction
attribute's allowed keywords are
as follows:
ltr
Treat input to the text preparation algorithm as left-to-right text.
rtl
Treat input to the text preparation algorithm as right-to-left text.
inherit
Default to the directionality of the canvas
element or Document
as appropriate.
The text preparation algorithm is as follows. It takes as input a string text
, a CanvasTextDrawingStyles
object target, and an optional length
maxWidth. It returns an array of glyph shapes, each positioned on a common coordinate
space, a physical alignment whose value is one of left, right, and
center, and an inline box. (Most callers of this algorithm ignore the
physical alignment and the inline box.)
If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.
Replace all ASCII whitespace in text with U+0020 SPACE characters.
Let font be the current font of target, as given
by that object's font
attribute.
Apply the appropriate step from the following list to determine the value of direction:
direction
attribute has the value "ltr
"direction
attribute has the value "rtl
"Document
with a non-null document elementForm 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 textAlign
and
textBaseline
values as follows:
Horizontal position:
textAlign
is left
textAlign
is start
and direction is
'ltr'textAlign
is end
and direction is 'rtl'textAlign
is right
textAlign
is end
and direction is 'ltr'textAlign
is start
and direction is
'rtl'textAlign
is center
Vertical position:
textBaseline
is top
textBaseline
is hanging
textBaseline
is middle
textBaseline
is alphabetic
textBaseline
is ideographic
textBaseline
is bottom
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.
Objects that implement the CanvasPath
interface have a path. A path has a list of zero or
more subpaths. Each subpath consists of a list of one or more points, connected by straight or
curved line segments, and a flag indicating whether the subpath is closed or not. A
closed subpath is one where the last point of the subpath is connected to the first point of the
subpath by a straight line. Subpaths with only one point are ignored when painting the path.
Paths have a need new subpath flag. When this flag is set, certain APIs create a new subpath rather than extending the previous one. When a path is created, its need new subpath flag must be set.
When an object implementing the CanvasPath
interface is created, its path must be initialized to zero subpaths.
moveTo
(x, y)moveTo
(x, y)Creates a new subpath with the given point.
closePath
()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.
lineTo
(x, y)lineTo
(x, y)Adds the given point to the current subpath, connected to the previous one by a straight line.
quadraticCurveTo
(cpx, cpy, x, y)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.
bezierCurveTo
(cp1x, cp1y, cp2x, cp2y, x, y)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.
arcTo
(x1, y1, x2, y2, radiusX [, radiusY, rotation ] )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, then 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, then 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 "IndexSizeError
" DOMException
if the given
radius is negative.
arc
(x, y, radius, startAngle, endAngle [, anticlockwise ] )arc
(x, y, radius, startAngle, endAngle [, anticlockwise ] )Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.
Throws an "IndexSizeError
" DOMException
if the given
radius is negative.
ellipse
(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] )ellipse
(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] )Adds points to the subpath such that the arc described by the circumference of the ellipse described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.
Throws an "IndexSizeError
" DOMException
if the given
radius is negative.
rect
(x, y, w, h)rect
(x, y, w, h)Adds a new closed subpath to the path, representing the given rectangle.
The following methods allow authors to manipulate the paths
of objects implementing the CanvasPath
interface.
For objects implementing the CanvasDrawPath
and CanvasTransform
interfaces, the points passed to the methods, and the resulting lines added to current
default path by these methods, must be transformed according to the current transformation matrix before being added to
the path.
The moveTo(x, y)
method, when invoked, must run these steps:
If either of the arguments are infinite or NaN, then abort these steps.
Create a new subpath with the specified point as its first (and only) point.
When the user agent is to ensure there is a subpath for a coordinate (x,
y) on a path, the user agent must check to see if
the path has its need new subpath flag set. If it
does, then the user agent must create a new subpath with the point (x, y) as
its first (and only) point, as if the moveTo()
method
had been called, and must then unset the path's need new
subpath flag.
The closePath()
method, when invoked,
must do nothing if the object's path 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 (possibly implied) 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 object's path.
The lineTo(x, y)
method, when invoked, must run these steps:
If either of the arguments are infinite or NaN, then abort these steps.
If the object's path has no subpaths, then ensure there is a subpath for (x, y).
Otherwise, connect the last point in the subpath to the given point (x, y) using a straight line, and then add the given point (x, y) to the subpath.
The quadraticCurveTo(cpx,
cpy, x, y)
method, when invoked, must run these
steps:
If any of the arguments are infinite or NaN, then abort these steps.
Ensure there is a subpath for (cpx, cpy)
Connect the last point in the subpath to the given point (x, y) using a quadratic Bézier curve with control point (cpx, cpy). [BEZIER]
Add the given point (x, y) to the subpath.
The bezierCurveTo(cp1x,
cp1y, cp2x, cp2y, x, y)
method, when invoked, must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Ensure there is a subpath for (cp1x, cp1y).
Connect the last point in the subpath to the given point (x, y) using a cubic Bézier curve with control points (cp1x, cp1y) and (cp2x, cp2y). [BEZIER]
Add the point (x, y) to the subpath.
The arcTo(x1, y1, x2,
y2, radiusX, radiusY, rotation)
method,
when invoked, must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Ensure there is a subpath for (x1, y1).
If either radiusX or radiusY are negative, then throw an
"IndexSizeError
" DOMException
.
If radiusY is omitted, then set radiusY to radiusX.
Let the point (x0, y0) be the last point in the subpath, transformed by the inverse of the current transformation matrix (so that it is in the same coordinate system as the points passed to the method).
If the point (x0, y0) is equal to the point (x1, y1), or if the point (x1, y1) is equal to the point (x2, y2), or if both radiusX and radiusY are zero, then add the point (x1, y1) to the subpath, and connect that point to the previous point (x0, y0) by a straight line.
Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, then add the point (x1, y1) to the subpath, and connect that point to the previous point (x0, y0) by a straight line.
Otherwise, let The Arc be the shortest arc given by circumference of the ellipse that has radius radiusX on the major axis and radius radiusY on the minor axis, and whose semi-major axis is rotated rotation radians clockwise from the positive x-axis, and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), and that has a different point tangent to the half-infinite line that ends at the point (x1, y1) and crosses the point (x2, y2). The points at which this ellipse touches these two lines are called the start and end tangent points respectively. Connect the point (x0, y0) to the start tangent point by a straight line, adding the start tangent point to the subpath, and then connect the start tangent point to the end tangent point by The Arc, adding the end tangent point to the subpath.
The arc(x, y,
radius, startAngle, endAngle, anticlockwise)
and ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
methods draw arcs.
The arc()
method is equivalent to the ellipse()
method in the case where the two radii are equal.
When the arc()
method is invoked, it must act as if the
ellipse()
method had been invoked with the radiusX and radiusY arguments set to the value of the radius argument, the rotation argument set to zero, and the
other arguments set to the same values as their identically named arguments on the arc()
method.
The ellipse()
method, when invoked, must run these
steps:
If any of the arguments are infinite or NaN, then abort these steps.
If either radiusX or radiusY are negative, then throw an
"IndexSizeError
" DOMException
.
If the object's path has any subpaths, then add a straight line from the last point in the subpath to the start point of the arc.
Add the start and end points of the arc to the subpath, and connect them with an arc. The arc and its start and end points are defined as follows:
Consider an ellipse that has its origin at (x, y), that has a major-axis radius radiusX and a minor-axis radius radiusY, and that is rotated about its origin such that its semi-major axis is inclined rotation radians clockwise from the x-axis.
If anticlockwise is false and endAngle-startAngle is equal to or greater than 2π, or, if anticlockwise is true and startAngle-endAngle is equal to or greater than 2π, then the arc is the whole circumference of this ellipse, and the point at startAngle along this circle's circumference, measured in radians clockwise from the ellipse's semi-major axis, acts as both the start point and the end point.
Otherwise, the points at startAngle and endAngle along this circle's circumference, measured in radians clockwise from the ellipse's semi-major axis, are the start and end points respectively, and the arc is the path along the circumference of this ellipse from the start point to the end point, going anti-clockwise if anticlockwise is true, and clockwise otherwise. Since the points are on the ellipse, as opposed to being simply angles from zero, the arc can never cover an angle greater than 2π radians.
Even if the arc covers the entire circumference of the ellipse and there are no
other points in the subpath, the path is not closed unless the closePath()
method is appropriately invoked.
The rect(x, y, w,
h)
method, when invoked, must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Create a new subpath containing just the four points (x, y), (x+w, y), (x+w, y+h), (x, y+h), in that order, with those four points connected by straight lines.
Mark the subpath as closed.
Create a new subpath with the point (x, y) as the only point in the subpath.
Path2D
objectsSpec bugs: 21939
Path2D
objects can be used to declare paths that are then later used on
objects implementing the CanvasDrawPath
interface. In addition to many of the APIs
described in earlier sections, Path2D
objects have methods to combine paths, and to
add text to paths.
Path2D
()Creates a new empty Path2D
object.
Path2D
(path)Creates a new Path2D
object that is a copy of the argument.
Path2D
(paths [, fillRule ] )Creates a new Path2D
object that describes a path that outlines the given paths, using the given fill rule.
Path2D
(d)Creates a new path with the path described by the argument, interpreted as SVG path data. [SVG]
addPath
(path [, transform ] )Adds to the path the path given by the argument.
The Path2D()
constructor, when invoked, must return a
newly created Path2D
object.
The Path2D(path)
constructor, when invoked, must return a newly created Path2D
object, to which the
subpaths of the argument are added. (In other words, it returns a copy of the argument.)
The Path2D(paths,
fillRule)
constructor, when invoked, must run these steps:
Run the appropriate step from the following list, based on the constructor's second argument:
Let merged path be a path that consists of a set of non-overlapping subpaths that exactly outline the points from which, in any of the paths provided in the constructor's first argument, the number of times a half-infinite straight line drawn from that point crosses a subpath going in one direction is not equal to the number of times it crosses a subpath going in the other direction.
Let merged path be a path that consists of a set of non-overlapping subpaths that exactly outline the points from which, in any of the paths provided in the constructor's first argument, the number of times a half-infinite straight line drawn from that point crosses that path is odd.
The subpaths in merged path must be oriented such that for any point, the number of times a half-infinite straight line drawn from that point crosses a subpath is even if and only if the number of times a half-infinite straight line drawn from that same point crosses a subpath going in one direction is equal to the number of times it crosses a subpath going in the other direction.
Add all the subpaths in merged path to the Path2D
object.
Set the Path2D
object's need new subpath flag.
The Path2D(d)
constructor, when invoked, must run these steps:
Parse and interpret the d argument according to the SVG specification's rules for path data, thus obtaining an SVG path. [SVG]
The resulting path could be empty. SVG defines error handling rules for parsing and applying path data.
Let (x, y) be the last point in the SVG path.
Create a new Path2D
object and add all the subpaths in the SVG path, if any,
to that Path2D
object.
Create a new subpath in the Path2D
object with (x, y) as the only point in the subpath.
Return the Path2D
object as the constructed object.
The addPath(b,
transform)
method, when invoked on a Path2D
object
a, must run these steps:
If the Path2D
object b has no subpaths, then abort these
steps.
Create a copy of all the subpaths in b. Let this copy be known as c.
Let matrix be the result of creating a DOMMatrix
from a dictionary
transform.
Transform all the coordinates and lines in c by the transform matrix matrix.
Let (x, y) be the last point in the last subpath of c.
Add all the subpaths in c to a.
Create a new subpath in a with (x, y) as the only point in the subpath.
Spec bugs: 28333
Objects that implement the CanvasTransform
interface have a current
transformation matrix, as well as methods (described in this section) to manipulate it. When
an object implementing the CanvasTransform
interface is created, its transformation
matrix must be initialized to the identity transform.
The current transformation matrix is applied to coordinates when creating the
current default path, and when painting text, shapes, and Path2D
objects, on objects implementing the CanvasTransform
interface.
Most of the API uses DOMMatrix
objects rather than this API. This API
remains mostly for historical reasons.
The transformations must be performed in reverse order.
For instance, if a scale transformation that doubles the width is applied to the canvas, 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.
scale
(x, y)Changes the current transformation matrix to apply a scaling transformation with the given characteristics.
rotate
(angle)Changes the current transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.
translate
(x, y)Changes the current transformation matrix to apply a translation transformation with the given characteristics.
transform
(a, b, c, d, e, f)Changes the current transformation matrix to apply the matrix given by the arguments as described below.
getTransform
()Returns a copy of the current transformation matrix, as a newly created
DOMMatrix
object.
setTransform
(a, b, c, d, e, f)Changes the current transformation matrix to the matrix given by the arguments as described below.
setTransform
(transform)Changes the current transformation matrix to the matrix represented by
the passed DOMMatrixInit
dictionary.
resetTransform
()Changes the current transformation matrix to the identity transform.
The scale(x, y)
method, when invoked, must run these steps:
If either of the arguments are infinite or NaN, then abort these steps.
Add the scaling transformation described by the arguments to the current transformation matrix. 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,
when invoked, must run these steps:
If angle is infinite or NaN, then abort these steps.
Add the rotation transformation described by the argument to the current transformation matrix. The angle argument represents a clockwise rotation angle expressed in radians.
The translate(x,
y)
method, when invoked, must run these steps:
If either of the arguments are infinite or NaN, then abort these steps.
Add the translation transformation described by the arguments to the current transformation matrix. 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(a, b,
c, d, e, f)
method, when invoked, must
run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Replace the current transformation matrix with the result of multiplying the current transformation matrix with the matrix described by:
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 ought to be taken in particular with the order of the second and third arguments (b and c) as their order varies from API to API and APIs sometimes use the notation m12/m21 and sometimes m21/m12 for those positions.
The getTransform()
method, when
invoked, must return a newly created DOMMatrix
representing a copy of the
current transformation matrix matrix of the context.
This returned object is not live, so updating it will not affect the
current transformation matrix, and updating the current transformation
matrix will not affect an already returned DOMMatrix
.
The setTransform(a, b,
c, d, e, f)
method, when invoked, must
run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Reset the current transformation matrix to the identity matrix.
Invoke the transform(a, b, c,
d, e, f)
method with the same arguments.
The setTransform(transform)
method, when invoked,
must reset the current transformation matrix to the value represented by the result
of creating a DOMMatrix
from a
dictionary transform.
The resetTransform()
method,
when invoked, must reset the current transformation matrix to the identity
matrix.
Some methods on the CanvasDrawImage
and CanvasFillStrokeStyles
interfaces take the union type CanvasImageSource
as an argument.
This union type allows objects implementing any of the following interfaces to be used as image sources:
HTMLOrSVGImageElement
(img
or SVG image
elements)HTMLVideoElement
(video
elements)HTMLCanvasElement
(canvas
elements)ImageBitmap
Although not formally specified as such, SVG image
elements are expected to be implemented nearly identical to img
elements. That is,
SVG image
elements share the fundamental concepts and features of
img
elements.
The ImageBitmap
interface can be created from a number of other
image-representing types, including ImageData
.
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 image is an HTMLOrSVGImageElement
object that is in the broken state, then throw an
"InvalidStateError
" DOMException
, return aborted,
and abort these steps.
If image is an HTMLOrSVGImageElement
object that is not fully decodable, or if image is an
HTMLVideoElement
object whose readyState
attribute is either HAVE_NOTHING
or HAVE_METADATA
, then return bad and abort these
steps.
If image is an HTMLOrSVGImageElement
object with an
intrinsic width or intrinsic height (or both) equal to zero, then
return bad and abort these steps.
If image is an HTMLCanvasElement
object with either a horizontal
dimension or a vertical dimension equal to zero, then return bad and abort these
steps.
If image is an ImageBitmap
object with its
[[Detached]] internal slot value set to true, then throw an
"InvalidStateError
" DOMException
, return aborted,
and abort these steps.
Return good.
When a CanvasImageSource
object represents an HTMLOrSVGImageElement
,
the element's image must be used as the source image.
Specifically, when a CanvasImageSource
object represents an animated image in an
HTMLOrSVGImageElement
, the user agent must use the default image of the animation
(the one that the format defines is to be used when animation is not supported or is disabled),
or, if there is no such image, the first frame of the animation, when rendering the image for
CanvasRenderingContext2D
APIs.
When a CanvasImageSource
object represents an HTMLVideoElement
, then
the frame at the current playback position when the method with the argument is
invoked must be used as the source image when rendering the image for
CanvasRenderingContext2D
APIs, and the source image's dimensions must be the intrinsic width and intrinsic height of the media resource
(i.e. after any aspect-ratio correction has been applied).
When a CanvasImageSource
object represents an HTMLCanvasElement
, the
element's bitmap must be used as the source image.
When a CanvasImageSource
object represents an element that is being
rendered and that element has been resized, the original image data of the source image
must be used, not the image as it is rendered (e.g. width
and
height
attributes on the source element have no effect on how
the object is interpreted when rendering the image for CanvasRenderingContext2D
APIs).
When a CanvasImageSource
object represents an ImageBitmap
, the
object's bitmap image data must be used as the source image.
The image argument is not origin-clean if it is an
HTMLOrSVGImageElement
or HTMLVideoElement
whose origin is
not the same as the origin specified by the entry settings
object, or if it is an HTMLCanvasElement
whose bitmap's origin-clean flag is false.
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 CanvasGradient
or
CanvasPattern
object. Invalid values are ignored.
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 CanvasGradient
or
CanvasPattern
object. Invalid values are ignored.
Objects that implement the CanvasFillStrokeStyles
interface have attributes and
methods (defined in this section) that control how shapes are treated by the object.
The fillStyle
attribute represents the
color or style to use inside shapes, and the strokeStyle
attribute represents the color
or style to use for the lines around the shapes.
Both attributes can be either strings, CanvasGradient
s, or
CanvasPattern
s. On setting, strings must be parsed as CSS <color> values and the color assigned, and
CanvasGradient
and CanvasPattern
objects must be assigned themselves. [CSSCOLOR] If the value is a string but cannot be parsed as a CSS
<color> value, then it must be ignored, and the attribute must retain its previous
value.
If the new value is a CanvasPattern
object that is marked as not origin-clean, then the
CanvasRenderingContext2D
's origin-clean flag must be set to false.
When set to a CanvasPattern
or CanvasGradient
object, the assignment
is live, meaning that changes made to the object after the assignment do affect
subsequent stroking or filling of shapes.
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
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, 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 ASCII lower hex digits. 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 ASCII digits 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, if the alpha value is
greater than zero then a U+002E FULL STOP (representing the decimal point), if the alpha value is
greater than zero then one or more ASCII digits representing the fractional part of
the alpha, and finally a U+0029
RIGHT PARENTHESIS. User agents must express the fractional part of the alpha value, if any, with
the level of precision necessary for the alpha value, when reparsed, to be interpreted as the same
alpha value.
When the context is created, the fillStyle
and strokeStyle
attributes
must initially have the string value #000000
.
When the value is a color, it must not be affected by the transformation matrix when used to draw on bitmaps.
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 over the RGBA space without premultiplying the alpha value to find the color to use at that offset. Before the first stop, the color must be the color of the first stop. After the last stop, the color must be the color of the last stop. When there are no stops, the gradient is transparent black.
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 "IndexSizeError
" DOMException
if the offset
is out of range. Throws a "SyntaxError
" DOMException
if
the color cannot be parsed.
createLinearGradient
(x0, y0, x1, y1)Returns a CanvasGradient
object that represents a
linear gradient that paints along the line given by the
coordinates represented by the arguments.
createRadialGradient
(x0, y0, r0, x1, y1, r1)Returns a CanvasGradient
object that represents a
radial gradient that paints along the cone given by the circles
represented by the arguments.
If either of the radii are negative, throws an
"IndexSizeError
" DOMException
exception.
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
"IndexSizeError
" DOMException
must be thrown. If the
color cannot be parsed as a CSS <color> value, then a
"SyntaxError
" DOMException
must be thrown. 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. If multiple stops are added at the same
offset on a gradient, then 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).
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. The method, when invoked, must return a linear
CanvasGradient
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.
If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.
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 either of r0 or r1 are negative, then an
"IndexSizeError
" DOMException
must be thrown. Otherwise,
the method, when invoked, must return a radial CanvasGradient
initialized with the
two specified circles.
Radial gradients must be rendered by following these steps:
If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. 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 bitmap 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).
The resulting radial gradient must then be transformed as described by the current transformation matrix when rendering.
Gradients must be painted only where the relevant stroking or filling effects requires that they be drawn.
Patterns are represented by objects implementing the opaque CanvasPattern
interface.
createPattern
(image, repetition)Returns a CanvasPattern
object that uses the given image and repeats in the
direction(s) given by the repetition argument.
The allowed values for repetition are repeat
(both
directions), repeat-x
(horizontal only), repeat-y
(vertical only), and no-repeat
(neither). If the repetition argument is empty, the value repeat
is used.
If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no
data, throws an "InvalidStateError
" DOMException
.
setTransform
(transform)Sets the transformation matrix that will be used when rendering the pattern during a fill or stroke painting operation.
The createPattern(image,
repetition)
method, when invoked, must run these steps:
Let image be the first argument and repetition be the second argument.
Check the usability of the image argument. If this returns aborted, then an exception has been thrown and the method doesn't return anything; abort these steps. If it returns bad, then return null and abort these steps. Otherwise it returns good; continue with these steps.
If repetition is the empty string, then set it to "repeat
".
If repetition is not a case-sensitive match for one of
"repeat
", "repeat-x
", "repeat-y
", or "no-repeat
", then throw a
"SyntaxError
" DOMException
and abort these steps.
Create a new CanvasPattern
object with the image image
and the repetition behavior given by repetition.
If the image argument is not origin-clean, then mark the
CanvasPattern
object as not
origin-clean.
Return the CanvasPattern
object.
Modifying the image used when creating a CanvasPattern
object
after calling the createPattern()
method must
not affect the pattern(s) rendered by the CanvasPattern
object.
Patterns have a transformation matrix, which controls how the pattern is used when it is painted. Initially, a pattern's transformation matrix must be the identity transform.
The setTransform(transform)
method,
when invoked, must reset the pattern's transformation matrix to the value represented by the
result of creating a DOMMatrix
from a dictionary transform.
When a pattern is to be rendered within an area, the user agent must run the following steps to determine what is rendered:
Create an infinite transparent black bitmap.
Place a copy of the image on the bitmap, anchored such that its top left corner is at the
origin of the coordinate space, with one coordinate space unit per CSS
pixel of the image, then place repeated copies of this image horizontally to the left and
right, if the repetition behavior is "repeat-x
", or vertically up and
down, if the repetition behavior is "repeat-y
", or in all four
directions all over the bitmap, if the repetition behavior is "repeat
".
If the original image data is a bitmap image, then the value painted at a point in the area
of the repetitions is computed by filtering the original image data. When scaling up, if the
imageSmoothingEnabled
attribute is
set to false, then the image must be rendered using nearest-neighbor interpolation. Otherwise,
the user agent may use any filtering algorithm (for example bilinear interpolation or
nearest-neighbor). User agents which support multiple filtering algorithms may use the value of
the imageSmoothingQuality
attribute
to guide the choice of filtering algorithm. When such a filtering algorithm requires a pixel
value from outside the original image data, it must instead use the value from wrapping the
pixel's coordinates to the original image's dimensions. (That is, the filter uses 'repeat'
behavior, regardless of the value of the pattern's repetition behavior.)
Transform the resulting bitmap according to the pattern's transformation matrix.
Transform the resulting bitmap again, this time according to the current transformation matrix.
Replace any part of the image outside the area in which the pattern is to be rendered with transparent black.
The resulting bitmap is what is to be rendered, with the same origin and same scale.
If a radial gradient or repeated pattern is used when the transformation matrix is singular, then the resulting style must be transparent black (otherwise the gradient or pattern would be collapsed to a point or line, leaving the other pixels undefined). Linear gradients and solid colors always define all points even with singular transformation matrices.
Objects that implement the CanvasRect
interface provide the following methods for
immediately drawing rectangles to the bitmap. The methods each take four arguments; the first two
give the x and y coordinates of the top left of the rectangle, and the
second two give the width w and height h of the rectangle, respectively.
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 default path, and are subject to
the clipping region, and, with the exception of clearRect()
, also shadow
effects, global alpha, and global composition operators.
clearRect
(x, y, w, h)Clears all pixels on the bitmap in the given rectangle to transparent black.
fillRect
(x, y, w, h)Paints the given rectangle onto the bitmap, using the current fill style.
strokeRect
(x, y, w, h)Paints the box that outlines the given rectangle onto the bitmap, using the current stroke style.
The clearRect(x, y,
w, h)
method, when invoked, must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Let pixels be the set of pixels in the specified rectangle that also intersect the current clipping region.
Clear the pixels in pixels to a fully transparent black, erasing any previous image.
If either height or width are zero, this method has no effect, since the set of pixels would be empty.
The fillRect(x, y,
w, h)
method, when invoked, must must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
If either w or h are zero, then abort these steps.
Paint the specified rectangular area using the fillStyle
.
The strokeRect(x, y,
w, h)
method, when invoked, must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Take the result of tracing the path described below,
using the CanvasPathDrawingStyles
interface's line styles, and fill it with the
strokeStyle
.
If both w and h are zero, the path has a single subpath with just one point (x, y), and no lines, and this method thus has no effect (the trace a path algorithm returns an empty path in that case).
If just one of either w or h is zero, then the path has a single subpath consisting of two points, with coordinates (x, y) and (x+w, y+h), in that order, connected by a single straight line.
Otherwise, the path has a single subpath consisting of four points, with coordinates (x, y), (x+w, y), (x+w, y+h), and (x, y+h), connected to each other in that order by straight lines.
Support: canvas-textChrome for Android 56+Chrome 4+UC Browser for Android 11+iOS Safari 3.2+Firefox 3.5+IE 9+Samsung Internet 4+Opera Mini NoneAndroid Browser 2.1+Safari 4+Edge 12+Opera 10.5+
Source: caniuse.com
fillText
(text, x, y [, maxWidth ] )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.
measureText
(text)Returns a TextMetrics
object with the metrics of the given text in the current
font.
width
actualBoundingBoxLeft
actualBoundingBoxRight
fontBoundingBoxAscent
fontBoundingBoxDescent
actualBoundingBoxAscent
actualBoundingBoxDescent
emHeightAscent
emHeightDescent
hangingBaseline
alphabeticBaseline
ideographicBaseline
Returns the measurement described below.
Objects that implement the CanvasText
interface provide the following methods for
rendering text.
The fillText()
and strokeText()
methods take three or four arguments,
text, x, y, and optionally maxWidth, and render the
given text at the given (x, y) coordinates ensuring that the text
isn't wider than maxWidth if specified, using the current font
, textAlign
, and textBaseline
values. Specifically, when the methods
are invoked, the user agent must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Run the text preparation algorithm, passing it text, the object
implementing the CanvasText
interface, and, if the maxWidth argument was
provided, that argument. Let glyphs be the result.
Move all the shapes in glyphs to the right by x CSS pixels and down by y CSS pixels.
Paint the shapes given in glyphs, as transformed by the current transformation matrix, with each CSS pixel in the coordinate space of glyphs mapped to one coordinate space unit.
For fillText()
, fillStyle
must be applied to the shapes and strokeStyle
must be ignored. For strokeText()
, the reverse holds: strokeStyle
must be applied to the result of tracing the shapes using the object implementing the
CanvasText
interface for the line styles, and fillStyle
must be ignored.
These shapes are painted without affecting the current path, and are subject to shadow effects, global alpha, the clipping region, and global composition operators.
The measureText()
method takes one
argument, text. When the method is invoked, the user agent must run the
text preparation algorithm, passing it text and the object implementing
the CanvasText
interface, and then using the returned inline box must
create a new TextMetrics
object with its attributes set as described in the following
list.
If doing these measurements requires using a font that has an origin that is not the
same as that of the Document
object that owns the
canvas
element (even if "using a font" means just checking if that font has a
particular glyph in it before falling back to another font), then the method, when invoked, must
throw a "SecurityError
" DOMException
.
Otherwise, it must return the new TextMetrics
object.
[CSS]
width
attributeThe width of that inline box, in CSS pixels. (The text's advance width.)
actualBoundingBoxLeft
attributeThe distance parallel to the baseline from the alignment point given by the textAlign
attribute to the left side of the bounding
rectangle of the given text, in CSS pixels; positive numbers
indicating a distance going left from the given alignment point.
The sum of this value and the next (actualBoundingBoxRight
) can be wider than
the width of the inline box (width
), in
particular with slanted fonts where characters overhang their advance width.
actualBoundingBoxRight
attributeThe distance parallel to the baseline from the alignment point given by the textAlign
attribute to the right side of the bounding
rectangle of the given text, in CSS pixels; positive numbers
indicating a distance going right from the given alignment point.
fontBoundingBoxAscent
attributeThe distance from the horizontal line indicated by the textBaseline
attribute 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 have to have
a consistent height even if the exact text being rendered changes. The actualBoundingBoxAscent
attribute (and
its corresponding attribute for the descent) are useful when drawing a bounding box around
specific text.
fontBoundingBoxDescent
attributeThe distance from the horizontal line indicated by the textBaseline
attribute 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.
actualBoundingBoxAscent
attributeThe distance from the horizontal line indicated by the textBaseline
attribute to the top of the bounding
rectangle of the given text, in CSS pixels; positive numbers
indicating a distance going up from the given baseline.
This number can vary greatly based on the input text, even if the first font
specified covers all the characters in the input. For example, the actualBoundingBoxAscent
of a lowercase
"o" from an alphabetic baseline would be less than that of an uppercase "F". The value can
easily be negative; for example, the distance from the top of the em box (textBaseline
value "top
") to the top of the bounding rectangle when
the given text is just a single comma ",
" would likely (unless the font is
quite unusual) be negative.
actualBoundingBoxDescent
attributeThe distance from the horizontal line indicated by the textBaseline
attribute to the bottom of the bounding
rectangle of the given text, in CSS pixels; positive numbers
indicating a distance going down from the given baseline.
emHeightAscent
attributeThe distance from the horizontal line indicated by the textBaseline
attribute to the highest top of the em
squares in the line box, in CSS pixels; positive numbers
indicating that the given baseline is below the top of that em square (so this value will usually
be positive). Zero if the given baseline is the top of that em square; half the font size if the
given baseline is the middle of that em square.
emHeightDescent
attributeThe distance from the horizontal line indicated by the textBaseline
attribute to the lowest bottom of the em
squares in the line box, in CSS pixels; positive numbers
indicating that the given baseline is below the bottom of that em square (so this value will
usually be negative). (Zero if the given baseline is the bottom of that em square.)
hangingBaseline
attributeThe distance from the horizontal line indicated by the textBaseline
attribute 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.)
alphabeticBaseline
attributeThe distance from the horizontal line indicated by the textBaseline
attribute 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.)
ideographicBaseline
attributeThe distance from the horizontal line indicated by the textBaseline
attribute 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 might provide a way to render fragments of documents, rendered using CSS, straight to the canvas. This would be provided in preference to a dedicated way of doing multiline layout.
Objects that implement the CanvasDrawPath
interface have a current default
path. There is only one current default path, it is not part of the
drawing state. The current default path is a path, as described above.
beginPath
()Resets the current default path.
fill
( [ fillRule ] )fill
(path [, fillRule ] )Fills the subpaths of the current default path or the given path with the current fill style, obeying the given fill rule.
stroke
()stroke
(path)Strokes the subpaths of the current default path or the given path with the current stroke style.
clip
( [ fillRule ] )clip
(path [, fillRule ] )Further constrains the clipping region to the current default path or the given path, using the given fill rule to determine what points are in the path.
resetClip
()Unconstrains the clipping region.
isPointInPath
(x, y [, fillRule ] )isPointInPath
(path, x, y [, fillRule ] )Returns true if the given point is in the current default path or the given path, using the given fill rule to determine what points are in the path.
isPointInStroke
(x, y)isPointInStroke
(path, x, y)Returns true if the given point would be in the region covered by the stroke of the current default path or the given path, given the current stroke style.
Spec bugs: 28217
The beginPath()
method, when invoked,
must empty the list of subpaths in the context's current default path so that the it
once again has zero subpaths.
Where the following method definitions use the term intended path, it means the
Path2D
argument, if one was provided, or the current default path
otherwise.
When the intended path is a Path2D
object, the coordinates and lines of its
subpaths must be transformed according to the
current transformation matrix on the object implementing the
CanvasTransform
interface when used by these methods (without affecting the
Path2D
object itself). When the intended path is the current default
path, it is not affected by the transform. (This is because transformations already affect
the current default path when it is constructed, so applying it when it is painted as
well would result in a double transformation.)
The fill()
method, when invoked, must fill
all the subpaths of the intended path, using fillStyle
, and using the fill rule indicated
by the fillRule argument. Open subpaths must be implicitly closed when being filled
(without affecting the actual subpaths).
The stroke()
method, when invoked, must
trace the intended path, using this
CanvasPathDrawingStyles
object for the line styles, and then fill the resulting path
using the strokeStyle
attribute, using the non-zero winding rule.
As a result of how the algorithm to trace a path is defined, overlapping parts of the paths in one stroke operation are treated as if their union was what was painted.
The stroke style is affected by the transformation during painting, even if the intended path is the current default path.
Paths, when filled or stroked, must be painted without affecting the current default
path or any Path2D
objects, and must be subject to shadow effects, global
alpha, the clipping region, and global composition operators. (The effect
of transformations is described above and varies based on which path is being used.)
The clip()
method, when invoked, must
create a new clipping region by calculating the intersection of the current clipping
region and the area described by the intended path, using the fill rule indicated by
the fillRule argument. Open subpaths must be implicitly closed when computing the
clipping region, without affecting the actual subpaths. The new clipping region replaces the
current clipping region.
When the context is initialized, the clipping region must be set to the largest infinite surface (i.e. by default, no clipping occurs).
The resetClip()
method, when invoked,
must create a new clipping region that is the largest infinite surface. The new
clipping region replaces the current clipping region.
The isPointInPath()
method, when
invoked, 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 inside the intended path as determined by the fill rule
indicated by the fillRule argument; and must return false otherwise. Open subpaths must
be implicitly closed when computing the area inside the path, without affecting the actual
subpaths. Points on the path itself must be considered to be inside the path. If either of the
arguments are infinite or NaN, then the method must return false.
The isPointInStroke()
method,
when invoked, 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 inside the path that results from tracing the intended path, using the non-zero winding rule, and using the
CanvasPathDrawingStyles
interface for the line styles; and must return false
otherwise. Points on the resulting path must be considered to be inside the path. If either of the
arguments are infinite or NaN, then the method must return false.
This canvas
element has a couple of checkboxes. The path-related commands are
highlighted:
<canvas height=400 width=750> <label><input type=checkbox id=showA> Show As</label> <label><input type=checkbox id=showB> Show Bs</label> <!-- ... --> </canvas> <script> function drawCheckbox(context, element, x, y, paint) { context.save(); context.font = '10px sans-serif'; context.textAlign = 'left'; context.textBaseline = 'middle'; var metrics = context.measureText(element.labels[0].textContent); if (paint) { context.beginPath(); context.strokeStyle = 'black'; context.rect(x-5, y-5, 10, 10); context.stroke(); if (element.checked) { context.fillStyle = 'black'; context.fill(); } context.fillText(element.labels[0].textContent, x+5, y); } context.beginPath(); context.rect(x-7, y-7, 12 + metrics.width+2, 14); context.drawFocusIfNeeded(element); context.restore(); } function drawBase() { /* ... */ } function drawAs() { /* ... */ } function drawBs() { /* ... */ } function redraw() { var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); drawCheckbox(context, document.getElementById('showA'), 20, 40, true); drawCheckbox(context, document.getElementById('showB'), 20, 60, true); drawBase(); if (document.getElementById('showA').checked) drawAs(); if (document.getElementById('showB').checked) drawBs(); } function processClick(event) { var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); var x = event.clientX; var y = event.clientY; var node = event.target; while (node) { x -= node.offsetLeft - node.scrollLeft; y -= node.offsetTop - node.scrollTop; node = node.offsetParent; } drawCheckbox(context, document.getElementById('showA'), 20, 40, false); if (context.isPointInPath(x, y)) document.getElementById('showA').checked = !(document.getElementById('showA').checked); drawCheckbox(context, document.getElementById('showB'), 20, 60, false); if (context.isPointInPath(x, y)) document.getElementById('showB').checked = !(document.getElementById('showB').checked); redraw(); } document.getElementsByTagName('canvas')[0].addEventListener('focus', redraw, true); document.getElementsByTagName('canvas')[0].addEventListener('blur', redraw, true); document.getElementsByTagName('canvas')[0].addEventListener('change', redraw, true); document.getElementsByTagName('canvas')[0].addEventListener('click', processClick, false); redraw(); </script>
drawFocusIfNeeded
(element)drawFocusIfNeeded
(path, element)If the given element is focused, draws a focus ring around the current default path or the given path, following the platform conventions for focus rings.
scrollPathIntoView
()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.
CanvasUserInterface
interface provide the following
methods to control drawing focus rings and scrolling paths into view.
The drawFocusIfNeeded(element)
method, when invoked, must run these steps:
If element is not focused or is not a descendant of the element with whose context the method is associated, then abort these steps.
Draw a focus ring of the appropriate style along the intended path, following platform conventions.
Some platforms only draw focus rings around elements that have been focused from
the keyboard, and not those focused from the mouse. Other platforms simply don't draw focus
rings around some elements at all unless relevant accessibility features are enabled. This API
is intended to follow these conventions. User agents that implement distinctions based on the
manner in which the element was focused are encouraged to classify focus driven by the focus()
method based on the kind of user interaction event from which
the call was triggered (if any).
The focus ring should not be subject to the shadow effects, the
global alpha, the global composition operators, or any of
the members in the CanvasFillStrokeStyles
, CanvasPathDrawingStyles
,
CanvasTextDrawingStyles
interfaces, but should be subject to the
clipping region. (The effect of transformations is described above and varies based
on which path is being used.)
Inform the user that the focus is at the location given by the intended path. User agents may wait until the next time the event loop reaches its update the rendering step to optionally inform the user.
User agents should not implicitly close open subpaths in the intended path when drawing the focus ring.
This might be a moot point, however. For example, if the focus ring is drawn as an axis-aligned bounding rectangle around the points in the intended path, then whether the subpaths are closed or not has no effect. This specification intentionally does not specify precisely how focus rings are to be drawn: user agents are expected to honor their platform's native conventions.
The scrollPathIntoView()
method, when invoked, must run these steps:
Let the specified rectangle be the rectangle of the bounding box of the intended path.
Let notional child be a hypothetical element that is a rendered child
of the canvas
element whose dimensions are those of the specified
rectangle.
Scroll notional child into view with the align to top flag set.
Optionally, inform the user that the caret or selection (or both) cover the specified rectangle of the canvas. The user agent may wait until the next time the event loop reaches its update the rendering step to optionally inform the user.
"Inform the user", as used in this section, does not imply any persistent state change. It could mean, for instance, calling a system accessibility API to notify assistive technologies such as magnification tools so that the user's magnifier moves to the given area of the canvas. However, it does not associate the path with the element, or provide a region for tactile feedback, etc.
Objects that implement the CanvasDrawImage
interface have the drawImage
method to draw images.
This method can be invoked with three different sets of arguments:
drawImage(image, dx, dy)
drawImage(image, dx, dy, dw, dh)
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
drawImage
(image, dx, dy)drawImage
(image, dx, dy, dw, dh)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 image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no
data, throws an "InvalidStateError
" DOMException
.
When the drawImage()
method is invoked, the user
agent must run these steps:
If any of the arguments are infinite or NaN, then abort these steps.
Check the usability of the image argument. If this returns aborted, then an exception has been thrown and the method doesn't return anything; abort these steps. If it returns bad, then abort these steps without drawing anything. Otherwise it returns good; continue with these steps.
Establish the source and destination rectangles as follows:
If not specified, the dw and dh arguments must default to the values of sw and sh, interpreted such that one CSS pixel in the image is treated as one unit in the output bitmap's coordinate space. If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's intrinsic width in image pixels, and the image's intrinsic height in image pixels, respectively. If the image has no intrinsic dimensions, then the concrete object size must be used instead, as determined using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having neither a definite width nor height, nor any additional constraints, the object's intrinsic properties being those of the image argument, and the default object size being the size of the output bitmap. [CSSIMAGES]
The source rectangle is the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
The destination rectangle is the rectangle whose corners are the four points (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).
When the source rectangle is outside the source image, the source rectangle must be clipped to the source image and the destination rectangle must be clipped in the same proportion.
When the destination rectangle is outside the destination image (the output bitmap), the pixels that land outside the output bitmap are discarded, as if the destination was an infinite canvas whose rendering was clipped to the dimensions of the output bitmap.
If one of the sw or sh arguments is zero, then abort these steps. Nothing is painted.
Paint the region of the image argument specified by the source rectangle on the region of the rendering context's output bitmap specified by the destination rectangle, after applying the current transformation matrix to the destination rectangle.
The image data must be processed in the original direction, even if the dimensions given are negative.
When scaling up, if the imageSmoothingEnabled
attribute is set to
true, the user agent should attempt to apply a smoothing algorithm to the image data when it is
scaled. User agents which support multiple filtering algorithms may use the value of the imageSmoothingQuality
attribute to guide
the choice of filtering algorithm when the imageSmoothingEnabled
attribute is set to
true. Otherwise, the image must be rendered using nearest-neighbor interpolation.
This specification does not define the precise algorithm to use when scaling an
image down, or when scaling an image up when the imageSmoothingEnabled
attribute is set to
true.
When a canvas
element is drawn onto itself, the drawing
model requires the source to be copied before the image is drawn, so it is possible to
copy parts of a canvas
element onto overlapping parts of itself.
If the original image data is a bitmap image, then the value painted at a point in the destination rectangle is computed by filtering the original image data. The user agent may use any filtering algorithm (for example bilinear interpolation or nearest-neighbor). When the filtering algorithm requires a pixel value from outside the original image data, it must instead use the value from the nearest edge pixel. (That is, the filter uses 'clamp-to-edge' behavior.) When the filtering algorithm requires a pixel value from outside the source rectangle but inside the original image data, then the value from the original image data must be used.
Thus, scaling an image in parts or in whole will have the same effect. This does
mean that when sprites coming from a single sprite sheet are to be scaled, adjacent images in
the sprite sheet can interfere. This can be avoided by ensuring each sprite in the sheet is
surrounded by a border of transparent black, or by copying sprites to be scaled into temporary
canvas
elements and drawing the scaled sprites from there.
Images are painted without affecting the current path, and are subject to shadow effects, global alpha, the clipping region, and global composition operators.
If the image argument is not origin-clean, then set the
CanvasRenderingContext2D
's origin-clean flag to false.
ImageData
(sw, sh)createImageData
(sw, sh)Returns an ImageData
object with the given dimensions. All the pixels in the
returned object are transparent black.
Throws an "IndexSizeError
" DOMException
if either of
the width or height arguments are zero.
createImageData
(imagedata)Returns an ImageData
object with the same dimensions as the argument. All the
pixels in the returned object are transparent black.
ImageData
(data, sw [, sh ] )Returns an ImageData
object using the data provided in the Uint8ClampedArray
argument, interpreted using the given
dimensions.
As each pixel in the data is represented by four numbers, the length of the data needs to be a multiple of four times the given width. If the height is provided as well, then the length needs to be exactly the width times the height times 4.
Throws an "IndexSizeError
" DOMException
if the given
data and dimensions can't be interpreted consistently, or if either dimension is zero.
getImageData
(sx, sy, sw, sh)Returns an ImageData
object containing the image data for the given rectangle of
the bitmap.
Throws an "IndexSizeError
" DOMException
if the either
of the width or height arguments are zero.
width
height
Returns the actual dimensions of the data in the ImageData
object, in
pixels.
data
Returns the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.
putImageData
(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ] )Paints the data from the given ImageData
object onto the bitmap. If a dirty
rectangle is provided, only the pixels from that rectangle are painted.
The globalAlpha
and globalCompositeOperation
attributes, as
well as the shadow attributes, are ignored for the purposes of this method call; pixels in the
canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.
Throws an "InvalidStateError
" DOMException
if the
imagedata object's data's [[Detached]] internal slot value is true.
Objects that implement the CanvasImageData
interface provide the following methods
for reading and writing pixel data to the bitmap.
The ImageData()
constructors and the
createImageData()
methods are
used to instantiate new ImageData
objects.
ImageData
objects are cloneable objects.
Each ImageData
object's [[Clone]](targetRealm,
memory) internal method must run these steps:
Let inputData be the value of this's data
attribute.
Let clonedData be ? StructuredClone(inputData, targetRealm, memory).
Return the result of creating an
ImageData
object, with parameter pixelsPerRow set to the value of
this's width
attribute, rows set to
the value of this's height
attribute, and using
clonedData.
When the ImageData()
constructor is invoked with two
numeric arguments sw and sh, it must create an ImageData
object with parameter pixelsPerRow set to sw, and rows set
to sh. The image data of the newly created ImageData
object must be
intializedzed to transparent black. If both sw and sh are non-zero, then
return the new ImageData
object. If one or both of sw and sh
are zero, then the constructor must throw an "IndexSizeError
"
DOMException
instead.
When the ImageData()
constructor is invoked with its first
argument being an Uint8ClampedArray
source
and its second and optional third arguments being numeric arguments sw and
sh, it must run these steps:
Let length be the number of bytes in source.
If length is not a non-zero integral multiple of four, then throw an
"InvalidStateError
" DOMException
and abort these
steps.
Let length be length divided by four.
If length is not an integral multiple of sw, then throw an
"IndexSizeError
" DOMException
and abort these steps.
At this step, the length is guaranteed to be greater than zero (otherwise the second step above would have aborted the steps), so if sw is zero, this step will throw the exception and abort these steps.
Let height be length divided by sw.
If the sh argument was not omitted, and its value is not equal to
height, then throw an "IndexSizeError
"
DOMException
and abort these steps.
Create an ImageData
object, with parameter pixelsPerRow
set to sw, rows set to sh, and using source.
Return the newly created ImageData
object.
The resulting object's data is not a copy of source, it's
the actual Uint8ClampedArray
object passed as the
first argument to the constructor.
When the createImageData()
method is
invoked with two numeric arguments sw and sh, it must create an
ImageData
object, with parameter pixelsPerRow set to the
absolute magnitude of sw, and parameter rows set to the absolute magnitude
of sh. Initialize the image data of the new ImageData
object to
transparent black. If both sw and sh are non-zero, then return
the new ImageData
object. If one or both of sw and sh are
zero, then throw an "IndexSizeError
" DOMException
instead.
When the createImageData()
method is
invoked with a single imagedata argument, it must create an
ImageData
object, with parameter pixelsPerRow set to the value of
the width
attribute of the ImageData
object passed as the argument, and the rows parameter set to the value of the
height
attribute.
Initialize the image data of the new ImageData
object to transparent black. Return
the newly created ImageData
object.
The getImageData(sx,
sy, sw, sh)
method, when invoked, must,
if either the sw or sh arguments are zero, throw an
"IndexSizeError
" DOMException
; otherwise,
if the CanvasRenderingContext2D
's origin-clean flag is set to false, it must throw a
"SecurityError
" DOMException
;
otherwise, it must create an ImageData
object, with parameter
pixelsPerRow set to sw, and parameter rows set to sh.
Set the pixel values of the image data of the newly created ImageData
object to
represent the output bitmap for the area of that bitmap denoted by the rectangle
whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx,
sy+sh), in the bitmap's coordinate space units.
Pixels outside the output bitmap must be set to transparent black. Pixel values
must not be premultiplied by alpha.
When the user agent is required to create an ImageData
object, given a
positive integer number of rows rows, a positive integer number of pixels per row
pixelsPerRow, and an optional Uint8ClampedArray
source, it must run these
steps:
Let imageData be a new uninitialized ImageData object.
If source is specified, then assign the data
attribute of imageData to
source.
If source is not specified, then initialize the data
attribute of imageData to a new Uint8ClampedArray
object. The Uint8ClampedArray
object must use a new Canvas
Pixel ArrayBuffer
for its storage, and must have a
zero start offset and a length equal to the length of its storage, in bytes. The Canvas
Pixel ArrayBuffer
must have the correct size to
store rows × pixelsPerRow pixels.
If the Canvas Pixel ArrayBuffer
cannot be
allocated, then rethrow the RangeError
thrown by JavaScript,
and abort these steps.
Initialize the width
attribute of
imageData to pixelsPerRow.
Initialize the height
attribute of
imageData to rows.
Return imageData.
A Canvas Pixel ArrayBuffer
is an ArrayBuffer
whose data is represented in left-to-right order, row
by row top to bottom, starting with the top left, with each pixel's red, green, blue, and alpha
components being given in that order for each pixel. Each component of each pixel represented in
this array must be in the range 0..255, representing the 8 bit value for that component. The
components must be assigned consecutive indices starting with 0 for the top left pixel's red
component.
The putImageData()
method writes
data from ImageData
structures back to the rendering context's output
bitmap. Its arguments are: imagedata, dx, dy,
dirtyX, dirtyY, dirtyWidth, and dirtyHeight.
When the last four arguments to this method are omitted, they must be assumed to have the
values 0, 0, the width
member of the imagedata structure, and the height
member of the imagedata structure, respectively.
The method, when invoked, must act as follows:
If imagedata's data
attribute value's
[[Detached]] internal slot value is true, then throw an
"InvalidStateError
" DOMException
and abort these
steps.
If dirtyWidth is negative, then let dirtyX be dirtyX+dirtyWidth, and let dirtyWidth be equal to the absolute magnitude of dirtyWidth.
If dirtyHeight is negative, then let dirtyY be dirtyY+dirtyHeight, and let dirtyHeight be equal to the absolute magnitude of dirtyHeight.
If dirtyX is negative, then let dirtyWidth be dirtyWidth+dirtyX, and let dirtyX be zero.
If dirtyY is negative, then let dirtyHeight be dirtyHeight+dirtyY, and let dirtyY be zero.
If dirtyX+dirtyWidth is greater than the width
attribute of the imagedata argument, then
let dirtyWidth be the value of that width
attribute, minus the value of dirtyX.
If dirtyY+dirtyHeight is greater than the height
attribute of the imagedata argument, then
let dirtyHeight be the value of that height
attribute, minus the value of dirtyY.
If, after those changes, either dirtyWidth or dirtyHeight are negative or zero, then abort these steps without affecting any bitmaps.
For all integer values of x and y where dirtyX ≤ x < dirtyX+dirtyWidth and dirtyY ≤ y < dirtyY+dirtyHeight, copy the
four channels of the pixel with coordinate (x, y) in
the imagedata data structure's Canvas Pixel
ArrayBuffer
to the pixel with coordinate (dx+x, dy+y)
in the rendering context's output bitmap.
The handling of pixel rounding when the specified coordinates are not integers 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), p, q);
...for any value of x, y, w, and h and where p is the smaller of x and the sum of x and w, and q is the smaller of y and the sum of y and h; and except that the following two calls:
context.createImageData(w, h); context.getImageData(0, 0, w, h);
...must return ImageData
objects with the same dimensions as each other, for any
value of w and h. In other words, while user agents may
round the arguments of these methods, any rounding performed must be performed consistently for
all of the methods described in this section. (The constructors only work with integer
values.)
Due to the lossy nature of converting to and from premultiplied alpha color
values, pixels that have just been set using putImageData()
might be returned to an equivalent
getImageData()
as different values.
The current path, transformation matrix, shadow attributes, global alpha, the clipping region, and global composition operator must not affect the methods described in this section.
In the following example, the script generates an ImageData
object so that it can
draw onto it.
// canvas is a reference to a <canvas> element var context = canvas.getContext('2d'); // create a blank slate var data = context.createImageData(canvas.width, canvas.height); // create some plasma FillPlasma(data, 'green'); // green plasma // add a cloud to the plasma AddCloud(data, data.width/2, data.height/2); // put a cloud in the middle // paint the plasma+cloud on the canvas context.putImageData(data, 0, 0); // support methods function FillPlasma(data, color) { ... } function AddCloud(data, x, y) { ... }
Here is an example of using getImageData()
and putImageData()
to implement an edge detection
filter.
<!DOCTYPE HTML> <html lang="en"> <head> <title>Edge detection demo</title> <script> var image = new Image(); function init() { image.onload = demo; image.src = "image.jpeg"; } function demo() { var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); // draw the image onto the canvas context.drawImage(image, 0, 0); // get the image data to manipulate var input = context.getImageData(0, 0, canvas.width, canvas.height); // get an empty slate to put the data into var output = context.createImageData(canvas.width, canvas.height); // alias some variables for convenience // In this case input.width and input.height // match canvas.width and canvas.height // but we'll use the former to keep the code generic. var w = input.width, h = input.height; var inputData = input.data; var outputData = output.data; // edge detection for (var y = 1; y < h-1; y += 1) { for (var x = 1; x < w-1; x += 1) { for (var c = 0; c < 3; c += 1) { var i = (y*w + x)*4 + c; outputData[i] = 127 + -inputData[i - w*4 - 4] - inputData[i - w*4] - inputData[i - w*4 + 4] + -inputData[i - 4] + 8*inputData[i] - inputData[i + 4] + -inputData[i + w*4 - 4] - inputData[i + w*4] - inputData[i + w*4 + 4]; } outputData[(y*w + x)*4 + 3] = 255; // alpha } } // put the image data back after manipulation context.putImageData(output, 0, 0); } </script> </head> <body onload="init()"> <canvas></canvas> </body> </html>
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.
globalCompositeOperation
[ = value ]Returns the current composition operation, from the values defined in the Compositing and Blending specification. [COMPOSITE].
Can be set, to change the composition operation. Unknown values are ignored.
All drawing operations on an object which implements the CanvasCompositing
interface 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 output
bitmap. 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, including
Infinity and Not-a-Number (NaN) values, then 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 the current composition operator, which controls how shapes and images are drawn onto the
output bitmap, once they have had globalAlpha
and the current transformation matrix
applied. The possible values are those defined in the Compositing and Blending specification, and
include the values source-over
and copy
.
[COMPOSITE]
Spec bugs: 27313
These values are all case-sensitive — they must be used exactly as defined. User agents must not recognize values that are not a case-sensitive match for one of the values given in the Compositing and Blending specification. [COMPOSITE]
On setting, if the user agent does not recognize the specified value, it must be ignored,
leaving the value of globalCompositeOperation
unaffected.
Otherwise, the attribute must be set to the given new value.
When the context is created, the globalCompositeOperation
attribute must
initially have the value source-over
.
imageSmoothingEnabled
[ = value ]Returns whether pattern fills and the drawImage()
method will attempt to smooth images if
their pixels don't line up exactly with the display, when scaling images up.
Can be set, to change whether images are smoothed (true) or not (false).
imageSmoothingQuality
[ = value ]Returns the current image-smoothing-quality preference.
Can be set, to change the preferred quality of image smoothing. The possible values are
"low
", "medium
" and "high
". Unknown values are ignored.
Objects that implement the CanvasImageSmoothing
interface have attributes that
control how image smoothing is performed.
The imageSmoothingEnabled
attribute, on getting, must return the last value it was set to. On setting, it must be set to the
new value. When the object implementing the CanvasImageSmoothing
interface is
created, the attribute must be set to true.
The imageSmoothingQuality
attribute, on getting, must return the last value it was set to. On setting, it must be set to the
new value. When the object implementing the CanvasImageSmoothing
interface is
created, the attribute must be set to "low
".
All drawing operations on an object which implements the CanvasShadowStyles
interface are affected by the four global shadow attributes.
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.
shadowOffsetX
[ = value ]shadowOffsetY
[ = value ]Returns the current shadow offset.
Can be set, to change the shadow offset. Values that are not finite numbers are ignored.
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.
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 cannot be parsed as a CSS <color> value then it must be ignored, and the attribute must retain its previous value. [CSSCOLOR]
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 level 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.
Shadows are only drawn if the opacity component of
the alpha component of the color of shadowColor
is
non-zero and either the shadowBlur
is non-zero, or
the shadowOffsetX
is non-zero, or the shadowOffsetY
is non-zero.
When shadows are drawn, they must be rendered as follows:
Let A be an infinite transparent black bitmap on which the source image for which a shadow is being created has been rendered.
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:
Let σ be half the value of shadowBlur
.
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.
If the current composition operation is copy
, then shadows
effectively won't render (since the shape will overwrite the shadow).
All drawing operations on an object which implements the CanvasFilters
interface are affected by the global filter
attribute.
filter
[ = value ]Returns the current filter.
Can be set, to change the filter. Values that cannot be parsed as a <filter-function-list> value are ignored.
The filter
attribute, on getting, must
return the last value it was successfully set to. The value must not be re-serialized. On setting,
if the new value is 'none' (not the empty string, null, or undefined), filters must be disabled
for the context. Otherwise, the value must be parsed as a
<filter-function-list> value. If the value cannot be parsed as a
<filter-function-list> value, where using property-independent style sheet
syntax like 'inherit' or 'initial' is considered an invalid value, then it must be ignored, and
the attribute must retain its previous value. When creating the object implementing the
CanvasFilters
interface, the attribute must be set to 'none'.
A <filter-function-list> value consists of a sequence of one or more filter functions or references to SVG filters. The input to the filter is used as the input to the first item in the list. Subsequent items take the output of the previous item as their input. [FILTERS]
Coordinates used in the value of the filter
attribute are interpreted such that one pixel is
equivalent to one SVG user space unit and to one canvas coordinate space unit. Filter coordinates
are not affected by the current transformation
matrix. The current transformation matrix affects only the input to the filter. Filters
are applied in the output bitmap's coordinate space.
When the value of the filter
attribute defines
lengths using percentages or using 'em' or 'ex' units, these must be
interpreted relative to the computed value of the 'font-size' property
of the font style source object at the time that the attribute is set, if it is an
element. If the computed values are undefined for a
particular case (e.g. because the font style source object is not an element or is
not being rendered), then the relative keywords must be interpreted relative to the
default value of the font
attribute. The 'larger' and
'smaller' keywords are not supported.
If the value of the filter
attribute refers to an
SVG filter in the same document, and this SVG filter changes, then the changed filter is used for
the next draw operation.
If the value of the filter
attribute refers to an
SVG filter in an external resource document and that document is not loaded when a drawing
operation is invoked, then the drawing operation must proceed with no filtering.
This section is non-normative.
Since drawing is performed using filter value 'none' until an externally-defined
filter has finished loading, authors might wish to determine whether such a filter
has finished loading before proceeding with a drawing operation. One way to accomplish
this is to load the externally-defined filter elsewhere within the same page in some
element that sends a load
event (for example, an SVG
use
element), and wait for the load
event to be
dispatched.
When a shape or image is painted, user agents must follow these steps, in the order given (or act as if they do):
Render the shape or image onto an infinite transparent black bitmap, creating image A, as described in the previous sections. For shapes, the current fill, stroke, and line styles must be honored, and the stroke must itself also be subjected to the current transformation matrix.
When the filter attribute is set to a value other than 'none' and all the
externally-defined filters it references, if any, are in documents that are currently loaded,
then use image A as the input to the filter
, creating image B. Otherwise, let
B be an alias for A.
When shadows are drawn, render the shadow from image B, using the current shadow styles, creating image C.
When shadows are drawn, multiply the alpha component of every pixel in C by globalAlpha
.
When shadows are drawn, composite C within the clipping region over the current output bitmap using the current composition operator.
Multiply the alpha component of every pixel in B by globalAlpha
.
Composite B within the clipping region over the current output bitmap using the current composition operator.
When compositing onto the output bitmap, pixels that would fall outside of the output bitmap must be discarded.
When a canvas is interactive, authors should include focusable elements in the element's fallback content corresponding to each focusable part of the canvas, as in the example above.
When rendering focus rings, to ensure that focus rings have the appearance of native focus
rings, authors should use the drawFocusIfNeeded()
method, passing it the
element for which a ring is being drawn. This method only draws the focus ring if the element is
focused, so that it can simply be called whenever drawing the element, without
checking whether the element is focused or not first.
In addition to drawing focus rings, authors should use the scrollPathIntoView()
method when an element in
the canvas is focused, to make sure it is visible on the screen (if applicable).
Authors should avoid implementing text editing controls
using the canvas
element. Doing so has a large number of disadvantages:
This is a huge amount of work, and authors are most strongly encouraged to avoid doing any of
it by instead using the input
element, the textarea
element, or the
contenteditable
attribute.
This section is non-normative.
Here is an example of a script that uses canvas to draw pretty glowing lines.
<canvas width="800" height="450"></canvas> <script> var context = document.getElementsByTagName('canvas')[0].getContext('2d'); var lastX = context.canvas.width * Math.random(); var lastY = context.canvas.height * Math.random(); var hue = 0; function line() { context.save(); context.translate(context.canvas.width/2, context.canvas.height/2); context.scale(0.9, 0.9); context.translate(-context.canvas.width/2, -context.canvas.height/2); context.beginPath(); context.lineWidth = 5 + Math.random() * 10; context.moveTo(lastX, lastY); lastX = context.canvas.width * Math.random(); lastY = context.canvas.height * Math.random(); context.bezierCurveTo(context.canvas.width * Math.random(), context.canvas.height * Math.random(), context.canvas.width * Math.random(), context.canvas.height * Math.random(), lastX, lastY); hue = hue + 10 * Math.random(); context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)'; context.shadowColor = 'white'; context.shadowBlur = 10; context.stroke(); context.restore(); } setInterval(line, 50); function blank() { context.fillStyle = 'rgba(0,0,0,0.1)'; context.fillRect(0, 0, context.canvas.width, context.canvas.height); } setInterval(blank, 40); </script>
The 2D rendering context for canvas
is often used for sprite-based games. The
following example demonstrates this:
Here is the source for this example:
<!DOCTYPE HTML> <meta charset="utf-8"> <title>Blue Robot Demo</title> <style> html { overflow: hidden; min-height: 200px; min-width: 380px; } body { height: 200px; position: relative; margin: 8px; } .buttons { position: absolute; bottom: 0px; left: 0px; margin: 4px; } </style> <canvas width="380" height="200"></canvas> <script> var Landscape = function (context, width, height) { this.offset = 0; this.width = width; this.advance = function (dx) { this.offset += dx; }; this.horizon = height * 0.7; // This creates the sky gradient (from a darker blue to white at the bottom) this.sky = context.createLinearGradient(0, 0, 0, this.horizon); this.sky.addColorStop(0.0, 'rgb(55,121,179)'); this.sky.addColorStop(0.7, 'rgb(121,194,245)'); this.sky.addColorStop(1.0, 'rgb(164,200,214)'); // this creates the grass gradient (from a darker green to a lighter green) this.earth = context.createLinearGradient(0, this.horizon, 0, height); this.earth.addColorStop(0.0, 'rgb(81,140,20)'); this.earth.addColorStop(1.0, 'rgb(123,177,57)'); this.paintBackground = function (context, width, height) { // first, paint the sky and grass rectangles context.fillStyle = this.sky; context.fillRect(0, 0, width, this.horizon); context.fillStyle = this.earth; context.fillRect(0, this.horizon, width, height-this.horizon); // then, draw the cloudy banner // we make it cloudy by having the draw text off the top of the // canvas, and just having the blurred shadow shown on the canvas context.save(); context.translate(width-((this.offset+(this.width*3.2)) % (this.width*4.0))+0, 0); context.shadowColor = 'white'; context.shadowOffsetY = 30+this.horizon/3; // offset down on canvas context.shadowBlur = '5'; context.fillStyle = 'white'; context.textAlign = 'left'; context.textBaseline = 'top'; context.font = '20px sans-serif'; context.fillText('WHATWG ROCKS', 10, -30); // text up above canvas context.restore(); // then, draw the background tree context.save(); context.translate(width-((this.offset+(this.width*0.2)) % (this.width*1.5))+30, 0); context.beginPath(); context.fillStyle = 'rgb(143,89,2)'; context.lineStyle = 'rgb(10,10,10)'; context.lineWidth = 2; context.rect(0, this.horizon+5, 10, -50); // trunk context.fill(); context.stroke(); context.beginPath(); context.fillStyle = 'rgb(78,154,6)'; context.arc(5, this.horizon-60, 30, 0, Math.PI*2); // leaves context.fill(); context.stroke(); context.restore(); }; this.paintForeground = function (context, width, height) { // draw the box that goes in front context.save(); context.translate(width-((this.offset+(this.width*0.7)) % (this.width*1.1))+0, 0); context.beginPath(); context.rect(0, this.horizon - 5, 25, 25); context.fillStyle = 'rgb(220,154,94)'; context.lineStyle = 'rgb(10,10,10)'; context.lineWidth = 2; context.fill(); context.stroke(); context.restore(); }; }; </script> <script> var BlueRobot = function () { this.sprites = new Image(); this.sprites.src = 'blue-robot.png'; // this sprite sheet has 8 cells this.targetMode = 'idle'; this.walk = function () { this.targetMode = 'walk'; }; this.stop = function () { this.targetMode = 'idle'; }; this.frameIndex = { 'idle': [0], // first cell is the idle frame 'walk': [1,2,3,4,5,6], // the walking animation is cells 1-6 'stop': [7], // last cell is the stopping animation }; this.mode = 'idle'; this.frame = 0; // index into frameIndex this.tick = function () { // this advances the frame and the robot // the return value is how many pixels the robot has moved this.frame += 1; if (this.frame >= this.frameIndex[this.mode].length) { // we've reached the end of this animation cycle this.frame = 0; if (this.mode != this.targetMode) { // switch to next cycle if (this.mode == 'walk') { // we need to stop walking before we decide what to do next this.mode = 'stop'; } else if (this.mode == 'stop') { if (this.targetMode == 'walk') this.mode = 'walk'; else this.mode = 'idle'; } else if (this.mode == 'idle') { if (this.targetMode == 'walk') this.mode = 'walk'; } } } if (this.mode == 'walk') return 8; return 0; }, this.paint = function (context, x, y) { if (!this.sprites.complete) return; // draw the right frame out of the sprite sheet onto the canvas // we assume each frame is as high as the sprite sheet // the x,y coordinates give the position of the bottom center of the sprite context.drawImage(this.sprites, this.frameIndex[this.mode][this.frame] * this.sprites.height, 0, this.sprites.height, this.sprites.height, x-this.sprites.height/2, y-this.sprites.height, this.sprites.height, this.sprites.height); }; }; </script> <script> var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); var landscape = new Landscape(context, canvas.width, canvas.height); var blueRobot = new BlueRobot(); // paint when the browser wants us to, using requestAnimationFrame() function paint() { context.clearRect(0, 0, canvas.width, canvas.height); landscape.paintBackground(context, canvas.width, canvas.height); blueRobot.paint(context, canvas.width/2, landscape.horizon*1.1); landscape.paintForeground(context, canvas.width, canvas.height); requestAnimationFrame(paint); } paint(); // but tick every 150ms, so that we don't slow down when we don't paint setInterval(function () { var dx = blueRobot.tick(); landscape.advance(dx); }, 100); </script> <p class="buttons"> <input type=button value="Walk" onclick="blueRobot.walk()"> <input type=button value="Stop" onclick="blueRobot.stop()"> <footer> <small> Blue Robot Player Sprite by <a href="https://johncolburn.deviantart.com/">JohnColburn</a>. Licensed under the terms of the Creative Commons Attribution Share-Alike 3.0 Unported license.</small> <small> This work is itself licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.</small> </footer>
ImageBitmap
rendering contextImageBitmapRenderingContext
is a performance-oriented interface that provides a
low overhead method for displaying the contents of ImageBitmap
objects. It uses
transfer semantics to reduce overall memory consumption. It also streamlines performance by
avoiding intermediate compositing, unlike the drawImage()
method of
CanvasRenderingContext2D
.
Using an img
element as an intermediate for getting an image resource into a
canvas, for example, would result in two copies of the decoded image existing in memory at the
same time: the img
element's copy, and the one in the canvas's backing store. This
memory cost can be prohibitive when dealing with extremely large images. This can be avoided by
using ImageBitmapRenderingContext
.
Using ImageBitmapRenderingContext
, here is how to transcode an image to the JPEG
format in a memory- and CPU-efficient way:
createImageBitmap(inputImageBlob).then(image => { const canvas = document.createElement('canvas'); const context = canvas.getContext('bitmaprenderer'); context.transferFromImageBitmap(image); canvas.toBlob(outputJPEGBlob => { // Do something with outputJPEGBlob. }, 'image/jpeg'); });
ImageBitmapRenderingContext
interfaceinterface ImageBitmapRenderingContext { readonly attribute HTMLCanvasElement canvas; void transferFromImageBitmap(ImageBitmap? bitmap); }; dictionary ImageBitmapRenderingContextSettings { boolean alpha = true; };
getContext
('bitmaprenderer' [, { [ alpha
: false ] } ] )Returns an ImageBitmapRenderingContext
object that is permanently bound to a
particular canvas
element.
If the alpha
setting is
provided and set to false, then the canvas is forced to always be opaque.
canvas
Returns the canvas
element that the context is bound to.
transferFromImageBitmap
(imageBitmap)Transfers the underlying bitmap data
from imageBitmap to context, and the bitmap becomes the contents of the
canvas
element to which context is bound.
transferFromImageBitmap
(
null)Replaces contents of the canvas
element to which context
is bound with a transparent black bitmap whose size corresponds to the width
and height
content attributes of the canvas
element.
The canvas
attribute
must return the value it was initialized to when the object was created.
An ImageBitmapRenderingContext
object has an output bitmap, which is a
reference to bitmap data.
An ImageBitmapRenderingContext
object has a bitmap mode, which can be set to
valid or blank. A value of valid indicates that the context's
output bitmap refers to
bitmap data that was acquired via transferFromImageBitmap()
.
A value blank indicates that the
context's output
bitmap is a default transparent bitmap.
An ImageBitmapRenderingContext
object also has an alpha flag, which can be set to true or
false. When an ImageBitmapRenderingContext
object has its alpha flag set to false, the contents
of the canvas
element to which the context is bound are obtained by
compositing the context's output bitmap onto an opaque
black bitmap of the same size using the source-over composite operation. If the alpha flag is set to true, then the
output bitmap is used
as the contents of the canvas
element to which the context is bound. [COMPOSITE]
The step of compositing over an opaque black bitmap ought to be elided whenever equivalent results can be obtained more efficiently by other means.
When a user agent is required to set an ImageBitmapRenderingContext
's output
bitmap, with a context argument that is an
ImageBitmapRenderingContext
object and an optional argument bitmap that
refers to bitmap data, it must run these
steps:
If a bitmap argument was not provided, then run these substeps:
Set context's bitmap mode to blank.
Let canvas be the canvas
element to which context
is bound.
Set context's output bitmap to be fully
transparent black with an intrinsic width equal to the numeric value of
canvas's width
attribute and an
intrinsic height equal to the numeric value of canvas's height
attribute, those values being interpreted in CSS pixels.
Set the output bitmap's origin-clean flag to true.
If a bitmap argument was provided, then run these substeps:
Set context's bitmap mode to valid.
Set context's output bitmap to refer to the same underlying bitmap data as bitmap, without making a copy.
The origin-clean flag of bitmap is included in the bitmap data to be referenced by context's output bitmap.
The ImageBitmapRenderingContext
creation algorithm, which is passed a
target (a canvas
element) and optionally some arguments, consists of
running the following steps:
If the algorithm was passed some arguments, then let arg be the first such argument. Otherwise, let arg be undefined.
Let settings be the result of coercing the arg context arguments for
ImageBitmapRenderingContext
.
Create a new ImageBitmapRenderingContext
object.
Initialize its canvas
attribute to point to
target.
Let the new ImageBitmapRenderingContext
object's output bitmap and
target's bitmap be a shared reference to the same bitmap.
Run the steps to set an ImageBitmapRenderingContext
's output
bitmap, using the new ImageBitmapRenderingContext
object as the
context argument, and with no bitmap argument.
Initialize context's alpha flag to true.
Process each of the members of settings as follows:
alpha
Return the new ImageBitmapRenderingContext
object.
When a user agent is required to coerce context arguments for
ImageBitmapRenderingContext
, it must run these steps:
Let input be the argument to coerce.
Let jsval be the result of converting input to a JavaScript value. If this throws an exception, then propagate the exception and abort these steps.
Let dict be the result of converting
jsval to the dictionary type ImageBitmapRenderingContextSettings
. If
this throws an exception, then propagate the exception and abort these steps.
Return dict.
The transferFromImageBitmap(imageBitmap)
method, when invoked, must run these steps:
Let bitmapContext be the ImageBitmapRenderingContext
object on
which the transferFromImageBitmap()
method was called.
If imageBitmap is null, then run the steps to set an ImageBitmapRenderingContext's output bitmap, with bitmapContext as the context argument and no bitmap argument, then abort these steps.
If the value of imageBitmap's [[Detached]] internal slot is set to
true, then throw an "InvalidStateError
" DOMException
and
abort these steps.
Run the steps to set an ImageBitmapRenderingContext
's output
bitmap, with the context argument equal to bitmapContext, and the
bitmap argument referring to imageBitmap's underlying bitmap data.
Set the value of imageBitmap's [[Detached]] internal slot to true.
Unset imageBitmap's bitmap data.
OffscreenCanvas
interfacetypedef (OffscreenCanvasRenderingContext2D or WebGLRenderingContext) OffscreenRenderingContext; dictionary ImageEncodeOptions { DOMString type = "image/png"; unrestricted double quality = 1.0; }; enum OffscreenRenderingContextType { "2d", "webgl" }; [Constructor([EnforceRange] unsigned long long width, [EnforceRange] unsigned long long height), Exposed=(Window,Worker)] interface OffscreenCanvas : EventTarget { attribute unsigned long long width; attribute unsigned long long height; OffscreenRenderingContext? getContext(OffscreenRenderingContextType contextType, any... arguments); ImageBitmap transferToImageBitmap(); Promise<Blob> convertToBlob(optional ImageEncodeOptions options); };
OffscreenCanvas
objects are used to create rendering contexts, much like an
HTMLCanvasElement
, but with no connection to the DOM. This makes it possible to
use canvas rendering contexts in workers.
An OffscreenCanvas
object may hold a weak reference to a placeholder canvas
element, which is
typically in the DOM, whose embedded content is provided by the OffscreenCanvas
object. The bitmap of the OffscreenCanvas
object is pushed to the placeholder canvas
element by
calling the commit()
method of the
OffscreenCanvas
object's rendering context. All rendering context types that
can be created by an OffscreenCanvas
object must implement a commit()
method. The exact behavior of the commit
method (e.g. whether it copies or transfers bitmaps) may vary, as defined by the rendering
contexts' respective specifications. Only the 2D context for offscreen canvases is defined
in this specification.
OffscreenCanvas
(width,
height)Returns a new OffscreenCanvas
object that is not linked to a placeholder canvas
element, and
whose bitmap's size is determined by the width and height arguments.
getContext
(contextType [, ... ] )Returns an object that exposes an API for drawing on the OffscreenCanvas
object. 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,
which is similar but distinct from the "2d
"
context that is created from a canvas
element. There is also a specification that
defines a "webgl
" context.
[WEBGL]
Returns null if the canvas has already been initialized with another context type (e.g.
trying to get a "2d
" context after getting a
"webgl
" context).
An OffscreenCanvas
object has an internal bitmap that is initialized when the object
is created. The width and height of the bitmap are
equal to the values of the width
and height
attributes of the OffscreenCanvas
object. Initially, all the bitmap's pixels are transparent black.
An OffscreenCanvas
object can have a rendering context bound to it. Initially,
it does not have a bound rendering context. To keep track of whether it has a rendering context
or not, and what kind of rendering context it is, an OffscreenCanvas
object also
has a context mode, which is initially none but can be changed to either 2d, webgl or detached by algorithms defined in this
specification.
The constructor OffscreenCanvas(width,
height)
, when invoked, must create a new OffscreenCanvas
object with its bitmap initialized to a rectangular
array of transparent black pixels of the dimensions specified by width and
height; and its width
and height
attributes initialized to width and
height respectively.
OffscreenCanvas
objects are transferable.
An OffscreenCanvas
object's [[Transfer]](targetRealm) internal method must run these
steps:
If this OffscreenCanvas
object's context mode is not equal to none, then throw an
"InvalidStateError
" DOMException
.
Let new be a new OffscreenCanvas
object in
targetRealm.
Initialize new's bitmap to a
rectangular array of transparent black pixels of the same dimensions as this
OffscreenCanvas
object's bitmap.
If this OffscreenCanvas
object has a placeholder canvas
element, then set
new's placeholder canvas
element to be a weak reference to this OffscreenCanvas
object's placeholder canvas
element.
Set this OffscreenCanvas
object's [[Detached]] internal slot value to
true.
Set this OffscreenCanvas
object's context mode to detached.
Unset this OffscreenCanvas
object's bitmap.
Return new.
The getContext(contextId,
arguments...)
method of an OffscreenCanvas
object, when
invoked, must run the steps in the cell of the following table whose column header describes the
OffscreenCanvas
object's context
mode and whose row header describes the method's first argument.
none | 2d | webgl | detached | |
---|---|---|---|---|
"2d "
|
Follow the steps to create an
offscreen 2D context defined in the section below, passing it the
OffscreenCanvas object and the method's arguments..., to obtain
an OffscreenCanvasRenderingContext2D object; if this does not throw an
exception, then set the OffscreenCanvas object's context mode to 2d, and return the new
OffscreenCanvasRenderingContext2D object.
| Return the same object as was returned the last time the method was invoked with this same first argument. | Return null. |
Throw an "InvalidStateError " DOMException .
|
"webgl "
|
Follow the instructions given in the WebGL specification's Context Creation section to
obtain either a WebGLRenderingContext or null; if the returned value is null,
then return null and abort these steps, otherwise, set the OffscreenCanvas
object's context mode to webgl, and return the
WebGLRenderingContext object. [WEBGL]
| Return null. | Return the same value as was returned the last time the method was invoked with this same first argument. |
Throw an "InvalidStateError " DOMException .
|
width
[
= value ]height
[
= value ]These attributes return the dimensions of the OffscreenCanvas
object's bitmap.
They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it).
If either the width
or height
attributes of an
OffscreenCanvas
object are set (to a new value or to the same value as before) and
the OffscreenCanvas
object's context
mode is 2d, then replace the
OffscreenCanvas
object's bitmap with a
new transparent black bitmap and reset the rendering context to its default state.
The new bitmap's dimensions are equal to the new values of the width
and height
attributes.
The resizing behavior for "webgl
"
contexts is defined in the WebGL specification. [WEBGL]
If an OffscreenCanvas
object whose dimensions were changed has
a placeholder canvas
element, then
the placeholder canvas
element's
intrinsic size will only be updated via the commit()
method of the OffscreenCanvas
object's rendering context.
convertToBlob
( [options] )Returns a promise that will fulfill with a new Blob
object representing a file
containing the image in the OffscreenCanvas
object.
The argument, if provided, is a dictionary that controls the encoding options of the image
file to be created. The type
field specifies the file format and has a default value of "image/png
"; that type
is also used if the requested type isn't supported. If the image format supports variable
quality (such as "image/jpeg
"), then the quality
field is a number in the range 0.0
to 1.0 inclusive indicating the desired quality level for the resulting image.
transferToImageBitmap
()Returns a newly created ImageBitmap
object with the image in the
OffscreenCanvas
object. The image in the OffscreenCanvas
object is
replaced with a new blank image.
The convertToBlob(options)
method,
when invoked, must run the following steps:
If the value of this OffscreenCanvas
object's [[Detached]]
internal slot is set to true, then return a promise rejected with an
"InvalidStateError
" DOMException
and abort these
steps.
If this OffscreenCanvas
object's context mode is 2d and the rendering context's bitmap's origin-clean flag is set to false, then return a
promise rejected with a "SecurityError
" DOMException
and
abort these steps.
If this OffscreenCanvas
object's bitmap has no pixels (i.e. either its
horizontal dimension or its vertical dimension is zero) then return a promise rejected with an
"IndexSizeError
" DOMException
and abort these
steps.
Let result be a new promise object.
Return result, and queue a task to run the remaining steps in parallel.
Let blob be a Blob
object, created in the relevant Realm of this OffscreenCanvas
object, representing a serialization of
this OffscreenCanvas
object's bitmap as
a file, passing the values of the type
and quality
fields of options, if
options was specified. [FILEAPI]
If blob is null, then reject result with an
"EncodingError
" DOMException
.
Otherwise, resolve result with blob.
The transferToImageBitmap()
method,
when invoked, must run the following steps:
If the value of this OffscreenCanvas
object's [[Detached]]
internal slot is set to true, then throw an "InvalidStateError
"
DOMException
and abort these steps.
If this OffscreenCanvas
object's context mode is set to none, then throw an
"InvalidStateError
" DOMException
and abort these
steps.
Let image be a newly created ImageBitmap
object that references
the same underlying bitmap data as this OffscreenCanvas
object's bitmap.
Set this OffscreenCanvas
object's bitmap to reference a newly created bitmap of the
same dimensions as the previous bitmap, and with its pixels initialized to transparent black,
or opaque black if the rendering context's alpha flag is set to false.
Return image.
[Exposed=(Window,Worker)] interface OffscreenCanvasRenderingContext2D { void commit(); readonly attribute OffscreenCanvas canvas; }; OffscreenCanvasRenderingContext2D implements CanvasState; OffscreenCanvasRenderingContext2D implements CanvasTransform; OffscreenCanvasRenderingContext2D implements CanvasCompositing; OffscreenCanvasRenderingContext2D implements CanvasImageSmoothing; OffscreenCanvasRenderingContext2D implements CanvasFillStrokeStyles; OffscreenCanvasRenderingContext2D implements CanvasShadowStyles; OffscreenCanvasRenderingContext2D implements CanvasFilters; OffscreenCanvasRenderingContext2D implements CanvasRect; OffscreenCanvasRenderingContext2D implements CanvasDrawPath; OffscreenCanvasRenderingContext2D implements CanvasDrawImage; OffscreenCanvasRenderingContext2D implements CanvasImageData; OffscreenCanvasRenderingContext2D implements CanvasPathDrawingStyles; OffscreenCanvasRenderingContext2D implements CanvasPath;
The OffscreenCanvasRenderingContext2D
is a rendering context
interface for drawing to the bitmap of an
OffscreenCanvas
object. It is similar to CanvasRenderingContext2D
,
with the following differences:
text rendering is not supported;
there is no support for user interface features;
its canvas
attribute refers to an
OffscreenCanvas
object rather than a canvas
element;
it has a commit()
method for pushing the
rendered image to the context's OffscreenCanvas
object's placeholder canvas
element.
An OffscreenCanvasRenderingContext2D
object has a bitmap that is initialized when the object is
created.
The bitmap has an origin-clean flag, which can be set to true or false. Initially, when one of these bitmaps is created, its origin-clean flag must be set to true.
An OffscreenCanvasRenderingContext2D
object also has an alpha flag, which can be set to true or false. Initially,
when the context is created, its alpha flag must be set to true. When an
OffscreenCanvasRenderingContext2D
object has its alpha flag set to false, then its alpha channel must be
fixed to 1.0 (fully opaque) for all pixels, and attempts to change the alpha component of any pixel
must be silently ignored.
An OffscreenCanvasRenderingContext2D
object has an associated
OffscreenCanvas
object, which is the OffscreenCanvas
object
from which the OffscreenCanvasRenderingContext2D
object was created.
commit
()Copies the rendering context's bitmap to
the bitmap of the placeholder canvas
element of the associated OffscreenCanvas
object. The copy
operation is asynchronous.
canvas
Returns the associated OffscreenCanvas
object.
The offscreen 2D context creation algorithm, which is passed a
target (an OffscreenCanvas
object) and optionally some arguments,
consists of running the following steps:
If the algorithm was passed some arguments, let arg be the first such argument. Otherwise, let arg be undefined.
Let settings be the result of coercing the arg context arguments for 2D.
Let context be a new OffscreenCanvasRenderingContext2D
object.
Set context's associated OffscreenCanvas
object to
target.
Process each of the members of settings as follows:
Set context's bitmap to a newly
created bitmap with the dimensions specified by the width
and height
attributes of target, and set
target's bitmap to the same bitmap (so that they are shared).
If context's alpha flag is set to true, initialize all the pixels of context's bitmap to transparent black. Otherwise, initialize the pixels to opaque black.
Return context.
The commit()
method, when invoked,
must run the following steps:
If this OffscreenCanvasRenderingContext2D
's associated
OffscreenCanvas
object does not have a placeholder canvas
element, abort
these steps.
Let image be a copy of this OffscreenCanvasRenderingContext2D
's
bitmap, including the value of its origin-clean flag.
Queue a task in the placeholder canvas
element's
relevant settings object's responsible event loop (which will be a
browsing context event loop) to set the placeholder canvas
element's
output bitmap to be a reference to image.
If image has different dimensions than the bitmap previously
referenced as the placeholder canvas
element's output bitmap, then this task will result in a change in
the placeholder canvas
element's intrinsic size, which can affect
document layout.
Implementations are encouraged to short-circuit the graphics update steps of
the browsing context event loop for the purposes of updating the
contents of a placeholder canvas
element to the display. This could mean, for example, that the commit()
method can copy the bitmap contents directly
to a graphics buffer that is mapped to the physical display location of the placeholder canvas
element. This or
similar short-circuiting approaches can significantly reduce display latency, especially in cases
where the commit()
method is invoked from a worker
and the event loop of the placeholder canvas
element's
browsing context is busy. However, such shortcuts can not have any
script-observable side-effects. This means that the committed bitmap still needs to be sent to
the placeholder canvas
element, in
case the element is used as a CanvasImageSource
, as an
ImageBitmapSource
, or in case toDataURL()
or toBlob()
are called on it.
The canvas
attribute, on getting,
must return this OffscreenCanvasRenderingContext2D
's associated
OffscreenCanvas
object.
The canvas
APIs must perform color correction at only two points: when rendering
images with their own gamma correction and color space information onto a bitmap, to convert the
image to the color space used by the bitmaps (e.g. using the 2D Context's drawImage()
method with an
HTMLOrSVGImageElement
object), and when rendering the actual canvas bitmap to the
output device.
Thus, in the 2D context, colors used to draw shapes onto the canvas will exactly
match colors obtained through the getImageData()
method.
The toDataURL()
method, when invoked, must not
include color space information in the resources they return. Where the output format allows it,
the color of pixels in resources created by toDataURL()
must match those returned by the getImageData()
method.
In user agents that support CSS, the color space used by a canvas
element must
match the color space used for processing any colors for that element in CSS.
The gamma correction and color space information of images must be handled in such a way that
an image rendered directly using an img
element would use the same colors as one
painted on a canvas
element that is then itself rendered. Furthermore, the rendering
of images that have no color correction information (such as those returned by the toDataURL()
method) must be rendered with no color
correction.
Thus, in the 2D context, calling the drawImage()
method to render the output of the toDataURL()
method to the canvas, given the appropriate
dimensions, has no visible effect.
When a user agent is to create a serialization of the bitmap as a file, given an optional type and quality, it must create an image file in the format given by type, or if type was not supplied, in the PNG format. If an error occurs during the creation of the image file (e.g. an internal encoder error), then the result of the serialization is null. [PNG]
The image file's pixel data must be the bitmap's pixel data scaled to one image pixel per coordinate space unit, and if the file format used supports encoding resolution metadata, the resolution must be given as 96dpi (one image pixel per CSS pixel).
If type is supplied, then it must be interpreted as a MIME type giving the format to use. If the type has any parameters, then it must be treated as not supported.
For example, the value "image/png
" would mean to generate a PNG
image, the value "image/jpeg
" would mean to generate a JPEG image, and the value
"image/svg+xml
" would mean to generate an SVG image (which would require that the
user agent track how the bitmap was generated, an unlikely, though potentially awesome,
feature).
User agents must support PNG ("image/png
"). User agents may support other types.
If the user agent does not support the requested type, then it must create the file using the PNG
format. [PNG]
User agents must convert the provided type to ASCII lowercase before establishing if they support that type.
For image types that do not support an alpha channel, the serialized image must be the bitmap image composited onto a solid black background using the source-over operator.
If type is an image format that supports variable quality (such as
"image/jpeg
") and quality is given, then, if Type(quality) is Number, and quality is in the range
0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level.
If Type(quality) is not Number, or if quality
is outside that range, the user agent must use its default quality value, as if the
quality argument had not been given.
The use of type-testing here, instead of simply declaring quality as
a Web IDL double
, is a historical artifact.
canvas
elementsThis section is non-normative.
Information leakage can occur if scripts from one origin can access information (e.g. read pixels) from images from another origin (one that isn't the same).
To mitigate this, bitmaps used with canvas
elements and ImageBitmap
objects are defined to have a flag indicating whether they are origin-clean. All bitmaps start with their origin-clean set to true. The flag is set to false
when cross-origin images are used.
The toDataURL()
, toBlob()
, and getImageData()
methods check the flag and will
throw a "SecurityError
" DOMException
rather than leak
cross-origin data.
The value of the origin-clean flag is
propagated from a source canvas
element's bitmap to a new ImageBitmap
object by createImageBitmap()
. Conversely, a
destination canvas
element's bitmap will have its origin-clean flags set to false by drawImage
if the source image is an
ImageBitmap
object whose bitmap has its origin-clean flag set to false.
The flag can be reset in certain situations; for example, when changing the value of the
width
or the height
content attribute of the canvas
element
to which a CanvasRenderingContext2D
is bound, the bitmap is
cleared and its origin-clean flag is reset.
When using an ImageBitmapRenderingContext
, the value of the origin-clean flag is propagated from
ImageBitmap
objects when they are transferred to the canvas
via transferFromImageBitmap().
Support: custom-elementsv1Chrome for Android 56+Chrome (limited) 54+UC Browser for Android NoneiOS Safari NoneFirefox NoneIE NoneSamsung Internet NoneOpera Mini NoneAndroid Browser NoneSafari (limited) 10.1+Opera 41+
Source: caniuse.com
This section is non-normative.
Custom elements provide a way for authors to build their own fully-featured DOM elements. Although authors could always use non-standard elements in their documents, with application-specific behavior added after the fact by scripting or similar, such elements have historically been non-conforming and not very functional. By defining a custom element, authors can inform the parser how to properly construct an element and how elements of that class should react to changes.
Custom elements are part of a larger effort to "rationalise the platform", by explaining existing platform features (like the elements of HTML) in terms of lower-level author-exposed extensibility points (like custom element definition). Although today there are many limitations on the capabilities of custom elements—both functionally and semantically—that prevent them from fully explaining the behaviors of HTML's existing elements, we hope to shrink this gap over time.
This section is non-normative.
For the purposes of illustrating how to create an autonomous custom element, let's define a custom element that encapsulates rendering a small icon for a country flag. Our goal is to be able to use it like so:
<flag-icon country="nl"></flag-icon>
To do this, we first declare a class for the custom element, extending
HTMLElement
:
class FlagIcon extends HTMLElement { constructor() { super(); this._countryCode = null; } static get observedAttributes() { return ["country"]; } attributeChangedCallback(name, oldValue, newValue) { // name will always be "country" due to observedAttributes this._countryCode = newValue; this._updateRendering(); } connectedCallback() { this._updateRendering(); } get country() { return this._countryCode; } set country(v) { this.setAttribute("country", v); } _updateRendering() { // Left as an exercise for the reader. But, you'll probably want to // check this.ownerDocument.defaultView to see if we've been // inserted into a document with a browsing context, and avoid // doing any work if not. } }
We then need to use this class to define the element:
customElements.define("flag-icon", FlagIcon);
At this point, our above code will work! The parser, whenever it sees the flag-icon
tag, will construct a new instance of our FlagIcon
class, and tell our code about its new country
attribute, which we then use to set the element's internal state and update its rendering (when
appropriate).
You can also create flag-icon
elements using the DOM API:
const flagIcon = document.createElement("flag-icon") flagIcon.country = "jp" document.body.appendChild(flagIcon)
Finally, we can also use the custom element constructor itself. That is, the above code is equivalent to:
const flagIcon = new FlagIcon() flagIcon.country = "jp" document.body.appendChild(flagIcon)
This section is non-normative.
Customized built-in elements are a distinct kind of custom element, which are defined slightly differently and used very differently compared to autonomous custom elements. They exist to allow reuse of behaviors from the existing elements of HTML, by extending those elements with new custom functionality. This is important since many of the existing behaviors of HTML elements can unfortunately not be duplicated by using purely autonomous custom elements. Instead, customized built-in elements allow the installation of custom construction behavior, lifecycle hooks, and prototype chain onto existing elements, essentially "mixing in" these capabilities on top of the already-existing element.
Customized built-in elements require a distinct syntax from autonomous custom elements because user agents and other software key off an element's local name in order to identify the element's semantics and behavior. That is, the concept of customized built-in elements building on top of existing behavior depends crucially on the extended elements retaining their original local name.
In this example, we'll be creating a customized built-in element named plastic-button
, which behaves like a normal button but gets fancy animation
effects added whenever you click on it. We start by defining a class, just like before, although
this time we extend HTMLButtonElement
instead of HTMLElement
:
class PlasticButton extends HTMLButtonElement { constructor() { super(); this.addEventListener("click", () => { // Draw some fancy animation effects! }); } }
When defining our custom element, we have to also specify the extends
option:
customElements.define("plastic-button", PlasticButton, { extends: "button" });
In general, the name of the element being extended cannot be determined simply by looking at
what element interface it extends, as many elements share the same interface (such as
q
and blockquote
both sharing HTMLQuoteElement
).
To use our customized built-in element, we use the is
attribute on a button
element:
<button is="plastic-button">Click Me!</button>
Trying to use a customized built-in element as an autonomous custom
element will not work; that is, <plastic-button>Click
me?</plastic-button>
will simply create an HTMLElement
with no special
behavior.
If you need to create a type-extended element programmatically, you can use the following form
of createElement()
:
const plasticButton = document.createElement("button", { is: "plastic-button" }); plasticButton.textContent = "Click me!";
And as before, the constructor will also work:
const plasticButton2 = new PlasticButton(); console.log(plasticButton2.localName); // will output "button" console.log(plasticButton2.getAttribute("is")); // will output "plastic-button"
Notably, all the of the ways in which button
is special apply to such "plastic
buttons" as well: their focus behavior, ability to participate in form submission, the disabled
attribute, and so on.
Customized built-in elements are designed to allow extension of existing HTML
elements that have useful user-agent supplied behavior or APIs. As such, they can only extend
existing HTML elements defined in this specification, and cannot extend legacy elements such as
bgsound
, blink
, isindex
, keygen
,
multicol
, nextid
, or spacer
that have been defined to use
HTMLUnknownElement
as their element interface.
One reason for this requirement is future-compatibility: if a customized built-in
element was defined that extended a currently-unknown element, for example combobox
, this would prevent this specification from defining a combobox
element in the future, as consumers of the derived customized
built-in element would have come to depend on their base element having no interesting
user-agent-supplied behavior.
Additionally, applet
elements cannot be extended, as they are in the process of
being removed from the Web platform.
This section is non-normative.
As specified below, and alluded to above, simply defining and using an element called
taco-button
does not mean that such elements represent buttons. That is, tools such as Web browsers, search engines,
or accessibility technology will not automatically treat the resulting element as a button just
based on its defined name.
To convey the desired button semantics to a variety of users, while still using an autonomous custom element, a number of techniques would need to be employed:
The addition of the tabindex
attribute would make the
taco-button
interactive content, thus making it
focusable. Note that if the
taco-button
were to become logically disabled, the tabindex
attribute would need to be removed.
The addition of various ARIA attributes helps convey semantics to accessibility
technology. For example, setting the role
attribute to
"button
" will convey the semantics that this is a
button, enabling users to successfully interact with the control using usual button-like
interactions in their accessibility technology. Setting the aria-label
attribute is necessary to give the button an
accessible name, instead of having accessibility
technology traverse its child text nodes and announce them. And setting aria-disabled
to "true
" when the button
is logically disabled conveys to accessibility technology the button's disabled state.
The addition of event handlers to handle commonly-expected button behaviors helps convey
the semantics of the button to Web browser users. In this case, the most relevant event handler
would be one that proxies appropriate keydown
events to
become click
events, so that you can activate the button both
with keyboard and by clicking.
In addition to any default visual styling provided for taco-button
elements, the visual styling will also need to be updated to reflect changes in logical state,
such as becoming disabled; that is, whatever stylesheet has rules for taco-button
will also need to have rules for taco-button[disabled]
.
With these points in mind, a full-featured taco-button
that took on the
responsibility of conveying button semantics (including the ability to be disabled) might look
something like this:
class TacoButton extends HTMLElement { static get observedAttributes() { return ["disabled"]; } constructor() { super(); this.addEventListener("keydown", e => { if (e.keyCode === 32 || e.keyCode === 13) { this.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); } }); this.addEventListener("click", e => { if (this.disabled) { e.preventDefault(); e.stopPropagation(); } }); this._observer = new MutationObserver(() => { this.setAttribute("aria-label", this.textContent); }); } connectedCallback() { this.setAttribute("role", "button"); this.setAttribute("tabindex", "0"); this._observer.observe(this, { childList: true, characterData: true, subtree: true }); } disconnectedCallback() { this._observer.disconnect(); } get disabled() { return this.hasAttribute("disabled"); } set disabled(v) { if (v) { this.setAttribute("disabled", ""); } else { this.removeAttribute("disabled"); } } attributeChangedCallback() { // only is called for the disabled attribute due to observedAttributes if (this.disabled) { this.removeAttribute("tabindex"); this.setAttribute("aria-disabled", "true"); } else { this.setAttribute("tabindex", "0"); this.setAttribute("aria-disabled", "false"); } } }
Even with this rather-complicated element definition, the element is not a pleasure to use for
consumers: it will be continually "sprouting" tabindex
and
aria-*
attributes of its own volition. This is because as of now
there is no way to specify default accessibility semantics or focus behavior for custom elements,
forcing the use of these attributes to do so (even though they are usually reserved for allowing
the consumer to override default behavior).
In contrast, a simple customized built-in element, as shown in the previous
section, would automatically inherit the semantics and behavior of the button
element, with no need to implement these behaviors manually. In general, for any elements with
nontrivial behavior and semantics that build on top of existing elements of HTML, customized built-in elements will be easier to
develop, maintain, and consume.
This section is non-normative.
Because element definition can occur at any time, a non-custom element could be created, and then later become a custom element after an appropriate definition is registered. We call this process "upgrading" the element, from a normal element into a custom element.
Upgrades enable scenarios where it may be
preferable for custom element definitions to be
registered after relevant elements has been initially created, such as by the parser. They allow
progressive enhancement of the content in the custom element. For example, in the following HTML
document the element definition for img-viewer
is loaded
asynchronously:
<!DOCTYPE html> <html lang="en"> <title>Image viewer example</title> <img-viewer filter="Kelvin"> <img src="images/tree.jpg" alt="A beautiful tree towering over an empty savannah"> </img-viewer> <script src="js/elements/img-viewer.js" async></script>
The definition for the img-viewer
element here is loaded using a
script
element marked with the async
attribute, placed after the <img-viewer>
tag in the markup. While the
script is loading, the img-viewer
element will be treated as an undefined
element, similar to a span
. Once the script loads, it will define the img-viewer
element, and the existing img-viewer
element on
the page will be upgraded, applying the custom element's definition (which presumably includes
applying an image filter identified by the string "Kelvin", enhancing the image's visual
appearance).
Note that upgrades only apply to elements in the document tree. (Formally, elements that are connected.) An element that is not inserted into a document will stay un-upgraded. An example illustrates this point:
<!DOCTYPE html> <html lang="en"> <title>Upgrade edge-cases example</title> <example-element></example-element> <script> "use strict"; const inDocument = document.querySelector("example-element"); const outOfDocument = document.createElement("example-element"); // Before the element definition, both are HTMLElement: console.assert(inDocument instanceof HTMLElement); console.assert(outOfDocument instanceof HTMLElement); class ExampleElement extends HTMLElement {} customElements.define("example-element", ExampleElement); // After element definition, the in-document element was upgraded: console.assert(inDocument instanceof ExampleElement); console.assert(!(outOfDocument instanceof ExampleElement)); document.body.appendChild(outOfDocument); // Now that we've moved the element into the document, it too was upgraded: console.assert(outOfDocument instanceof ExampleElement); </script>
When authoring custom element constructors, authors are bound by the following conformance requirements:
A parameter-less call to super()
must be the first statement in the
constructor body, to establish the correct prototype chain and this value before any
further code is run.
A return
statement must not appear anywhere inside the constructor
body, unless it is a simple early-return (return
or return
this
).
The constructor must not use the document.write()
or document.open()
methods.
The element's attributes and children must not be inspected, as in the non-upgrade case none will be present, and relying on upgrades makes the element less usable.
The element must not gain any attributes or children, as this violates the expectations of
consumers who use the createElement
or createElementNS
methods.
In general, work should be deferred to connectedCallback
as much as
possible—especially work involving fetching resources or rendering. However, note that connectedCallback
can be called more than once, so any initialization work that
is truly one-time will need a guard to prevent it from running twice.
In general, the constructor should be used to set up initial state and default values, and to set up event listeners and possibly a shadow root.
Several of these requirements are checked during element creation, either directly or indirectly, and failing to follow them will result in a custom element that cannot be instantiated by the parser or DOM APIs.
A custom element is an element that is custom. Informally, this means that its constructor and prototype are defined by the author, instead of by the user agent. This author-supplied constructor function is called the custom element constructor.
Two distinct types of custom elements can be defined:
An autonomous custom element, which is defined with no extends
option. These types of custom elements have a local name equal to their
defined name.
A customized built-in element, which is defined with an extends
option. These types of custom elements have a local name equal to the
value passed in their extends
option, and their defined name is used as the value of the
is
attribute, which therefore must be a valid
custom element name.
After a custom element is created,
changing the value of the is
attribute does not
change the element's behavior, as it is saved on the element as its is
value.
Autonomous custom elements have the following element definition:
is
attributeHTMLElement
)An autonomous custom element does not have any special meaning: it represents its children. A customized built-in element inherits the semantics of the element that it extends.
Any namespace-less attribute that is relevant to the element's functioning, as determined by
the element's author, may be specified on an autonomous custom element, so long as
the attribute name is XML-compatible and contains no ASCII upper alphas. The exception is the is
attribute,
which must not be specified on an autonomous custom element (and which will have no
effect if it is).
Customized built-in elements follow the
normal requirements for attributes, based on the elements they extend. To add custom
attribute-based behavior, use data-*
attributes.
A valid custom element name is a sequence of characters name that meets all of the following requirements:
name must match the PotentialCustomElementName
production:
PotentialCustomElementName ::=
[a-z] (PCENChar)* '-'
(PCENChar)*
PCENChar ::=
"-" | "." | [0-9] | "_" | [a-z] | #xB7 | [#xC0-#xD6] | [#xD8-#xF6] |
[#xF8-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x203F-#x2040] | [#x2070-#x218F] |
[#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
[#x10000-#xEFFFF]
This uses the EBNF notation from the XML specification. [XML]
name must not be any of the following:
annotation-xml
color-profile
font-face
font-face-src
font-face-uri
font-face-format
font-face-name
missing-glyph
The list of names above is the summary of all hyphen-containing element names from the applicable specifications, namely SVG and MathML. [SVG] [MATHML]
These requirements ensure a number of goals for valid custom element names:
They start with an ASCII lower alpha, ensuring that the HTML parser will treat them as tags instead of as text.
They do not contain any ASCII upper alphas, ensuring that the user agent can always treat HTML elements ASCII-case-insensitively.
They contain a hyphen, used for namespacing and to ensure forward compatibility (since no elements will be added to HTML, SVG, or MathML with hyphen-containing local names in the future).
They can always be created with createElement()
and createElementNS()
, which have restrictions that go
beyond the parser's.
Apart from these restrictions, a large variety of names is allowed, to give maximum
flexibility for use cases like <math-α>
or <emotion-😍>
.
A custom element definition describes a custom element and consists of:
sequence<DOMString>
connectedCallback
",
"disconnectedCallback
", "adoptedCallback
", and
"attributeChangedCallback
". The corresponding values are either a Web IDL
Function
callback function type value, or null. By default the
value of each entry is null.To look up a custom element definition, given a document, namespace, localName, and is, perform the following steps. They will return either a custom element definition or null:
If namespace is not the HTML namespace, return null.
If document does not have a browsing context, return null.
Let registry be document's browsing context's Window
's
CustomElementRegistry
object.
If there is custom element definition in registry with name and local name both equal to localName, return that custom element definition.
If there is a custom element definition in registry with name equal to is and local name equal to localName, return that custom element definition.
Return null.
CustomElementRegistry
interfaceEach Window
object is associated with a unique instance of a
CustomElementRegistry
object, allocated when the Window
object is
created.
Custom element registries are associated with Window
objects, instead
of Document
objects, since each custom element constructor inherits from
the HTMLElement
interface, and there is exactly one HTMLElement
interface per Window
object.
The customElements
attribute of the
Window
interface must return the CustomElementRegistry
object for that
Window
object.
interface CustomElementRegistry { [CEReactions] void define(DOMString name, Function constructor, optional ElementDefinitionOptions options); any get(DOMString name); Promise<void> whenDefined(DOMString name); }; dictionary ElementDefinitionOptions { DOMString extends; };
Every CustomElementRegistry
has a set of custom element definitions, initially empty. In general, algorithms in this
specification look up elements in the registry by any of name, local name, or constructor.
Every CustomElementRegistry
also has an element definition is running
flag which is used to prevent reentrant invocations of element definition. It is
initially unset.
Every CustomElementRegistry
also has a when-defined promise map,
mapping valid custom element names to promises. It
is used to implement the whenDefined()
method.
customElements
. define
(name,
constructor)customElements
. define
(name, constructor,
{ extends: baseLocalName })NotSupportedError
"
DOMException
will be thrown upon trying to extend a custom element or
an unknown element.customElements
. get
(name)customElements
. whenDefined
(name)SyntaxError
" DOMException
if not given a valid
custom element name.Element definition is a process of adding a custom element definition
to the CustomElementRegistry
. This is accomplished by the define()
method. When invoked, the define(name, constructor,
options)
method must run these steps:
If IsConstructor(constructor) is false, then throw a
TypeError
and abort these steps.
If name is not a valid custom element name, then throw a
"SyntaxError
" DOMException
and abort these steps.
If this CustomElementRegistry
contains an entry with name name, then throw a
"NotSupportedError
" DOMException
and abort these
steps.
If this CustomElementRegistry
contains an entry with constructor constructor,
then throw a "NotSupportedError
" DOMException
and abort
these steps.
Let localName be name.
Let extends be the value of the extends
member of
options, or null if no such member exists.
If extends is not null, then:
If extends is a valid custom element name, then throw a
"NotSupportedError
" DOMException
.
If the element interface for extends and the HTML
namespace is HTMLUnknownElement
(e.g., if extends does not
indicate an element definition in this specification), then throw a
"NotSupportedError
" DOMException
.
Set localName to extends.
If this CustomElementRegistry
's element definition is running
flag is set, then throw a "NotSupportedError
" DOMException
and abort these steps.
Set this CustomElementRegistry
's element definition is running
flag.
Run the following substeps while catching any exceptions:
Let prototype be Get(constructor, "prototype"). Rethrow any exceptions.
If Type(prototype) is not Object, then throw a
TypeError
exception.
Let lifecycleCallbacks be a map with the four keys "connectedCallback
", "disconnectedCallback
", "adoptedCallback
", and "attributeChangedCallback
", each
of which belongs to an entry whose value is null.
For each of the four keys callbackName in lifecycleCallbacks, in the order listed in the previous step:
Let callbackValue be Get(prototype, callbackName). Rethrow any exceptions.
If callbackValue is not undefined, then set the value of the entry in
lifecycleCallbacks with key callbackName to the result of converting callbackValue to the Web IDL
Function
callback type. Rethrow any exceptions from the
conversion.
Let observedAttributes be an empty sequence<DOMString>
.
If the value of the entry in lifecycleCallbacks with key "attributeChangedCallback
" is not null, then:
Let observedAttributesIterable be Get(constructor, "observedAttributes"). Rethrow any exceptions.
If observedAttributesIterable is not undefined, then set
observedAttributes to the result of converting observedAttributesIterable to a
sequence<DOMString>
. Rethrow any exceptions from the
conversion.
Then, perform the following substep, regardless of whether the above steps threw an exception or not:
Unset this CustomElementRegistry
's element definition is
running flag.
Finally, if the first set of substeps threw an exception, then rethrow that exception, and terminate this algorithm. Otherwise, continue onward.
Let definition be a new custom element definition with name name, local name localName, constructor constructor, observed attributes observedAttributes, and lifecycle callbacks lifecycleCallbacks.
Add definition to this CustomElementRegistry
.
Let document be this CustomElementRegistry
's relevant global object's associated Document
.
Let upgrade candidates be all elements that are shadow-including descendants of document, whose namespace
is the HTML namespace and whose local name is localName, in
shadow-including tree order. Additionally, if extends is non-null, only
include elements whose is
value is equal to name.
For each element element in upgrade candidates, enqueue a custom element upgrade reaction given element and definition.
If this CustomElementRegistry
's when-defined promise map
contains an entry with key name:
Let promise be the value of that entry.
Resolve promise with undefined.
Delete the entry with key name from this
CustomElementRegistry
's when-defined promise map.
When invoked, the get(name)
method must run these
steps:
If this CustomElementRegistry
contains an entry with name name, then return that
entry's constructor.
Otherwise, return undefined.
When invoked, the whenDefined(name)
method
must run these steps:
If name is not a valid custom element name, then return a new
promise rejected with a "SyntaxError
" DOMException
and
abort these steps.
If this CustomElementRegistry
contains an entry with name name, then return a new
promise resolved with undefined and abort these steps.
Let map be this CustomElementRegistry
's when-defined
promise map.
If map does not contain an entry with key name, create an entry in map with key name and whose value is a new promise.
Let promise be the value of the entry in map with key name.
Return promise.
The whenDefined()
method can be
used to avoid performing an action until all appropriate custom
elements are defined. In this example, we
combine it with the :defined
pseudo-class to hide a
dynamically-loaded article's contents until we're sure that all of the autonomous custom elements it uses are defined.
articleContainer.hidden = true; fetch(articleURL) .then(response => response.text()) .then(text => { articleContainer.innerHTML = text; return Promise.all( [...articleContainer.querySelectorAll(":not(:defined)")] .map(el => customElements.whenDefined(el.localName)) ); }) .then(() => { articleContainer.hidden = false; });
To upgrade an element, given as input a custom element definition definition and an element element, run the following steps:
If element is custom, abort these steps.
This can occur due to reentrant invocation of this algorithm, as in the following example:
<!DOCTYPE html> <x-foo id="a"></x-foo> <x-foo id="b"></x-foo> <script> // Defining enqueues upgrade reactions for both "a" and "b" customElements.define("x-foo", class extends HTMLElement { constructor() { super(); const b = document.querySelector("#b"); b.remove(); // While this constructor is running for "a", "b" is still // undefined, and so inserting it into the document will enqueue a // second upgrade reaction for "b" in addition to the one enqueued // by defining x-foo. document.body.appendChild(b); } }) </script>
This step will thus bail out the algorithm early when upgrade an element is invoked
with "b
" a second time.
If element's custom element state is "failed
", then abort these steps.
For each attribute in element's attribute list, in
order, enqueue a custom element callback reaction with element, callback
name "attributeChangedCallback
", and an argument list containing
attribute's local name, null, attribute's value, and attribute's
namespace.
If element is connected, then enqueue a custom element
callback reaction with element, callback name "connectedCallback
", and an empty argument list.
Add element to the end of definition's construction stack.
Let C be definition's constructor.
Run the following substeps while catching any exceptions:
Let constructResult be Construct(C).
If C non-conformantly
uses an API decorated with the [CEReactions]
extended
attribute, then the reactions enqueued at the beginning of this algorithm will execute during
this step, before C finishes and control returns to this algorithm. Otherwise, they
will execute after C and the rest of the upgrade process finishes.
If SameValue(constructResult, element) is false,
then throw an "InvalidStateError
" DOMException
.
This can occur if C constructs another instance of the same custom
element before calling super()
, or if C uses JavaScript's
return
-override feature to return an arbitrary object from the
constructor.
Then, perform the following substep, regardless of whether the above steps threw an exception or not:
Remove the last entry from the end of definition's construction stack.
Assuming C calls super()
(as it will if it is conformant), and that the call succeeds, this will be
the already
constructed marker that replaced the element we pushed at the beginning
of this algorithm. (The HTML element constructor
carries out this replacement.)
If C does not call super()
(i.e. it is not conformant), or if any step in the HTML element constructor throws, then this entry will
still be element.
Finally, if the above steps threw an exception, then:
Set element's custom element state to "failed
".
Empty element's custom element reaction queue.
Rethrow the exception, and terminate this algorithm.
Set element's custom element state to "custom
".
Set element's custom element definition to definition.
To try to upgrade an element, given as input an element element, run the following steps:
Let definition be the result of looking up a custom element definition given element's node
document, element's namespace, element's local name, and
element's is
value.
If definition is not null, then enqueue a custom element upgrade reaction given element and definition.
A custom element possesses the ability to respond to certain occurrences by running author code:
When upgraded, its constructor is run.
When it becomes connected, its connectedCallback
is
run.
When it becomes disconnected, its disconnectedCallback
is run.
When it is adopted into a new document, its adoptedCallback
is run.
When any of its attributes are changed, appended, removed, or replaced, its attributeChangedCallback
is run.
We call these reactions collectively custom element reactions.
The way in which custom element reactions are invoked is done with special care, to avoid running author code during the middle of delicate operations. Effectively, they are delayed until "just before returning to user script". This means that for most purposes they appear to execute synchronously, but in the case of complicated composite operations (like cloning, or range manipulation), they will instead be delayed until after all the relevant user agent processing steps have completed, and then run together as a batch.
Additionally, the precise ordering of these reactions is managed via a somewhat-complicated stack-of-queues system, described below. The intention behind this system is to guarantee that custom element reactions always are invoked in the same order as their triggering actions, at least within the local context of a single custom element. (Because custom element reaction code can perform its own mutations, it is not possible to give a global ordering guarantee across multiple elements.)
Each unit of related similar-origin browsing contexts has a custom element reactions stack, which is initially empty. The current element queue is the element queue at the top of the custom element reactions stack. Each item in the stack is an element queue, which is initially empty as well. Each item in an element queue is an element. (The elements are not necessarily custom yet, since this queue is used for upgrades as well.)
Each custom element reactions stack has an associated backup element
queue, which an initially-empty element queue. Elements are pushed onto the
backup element queue during operations that affect the DOM without going through an
API decorated with [CEReactions]
, or through the parser's
create an element for the token algorithm. An example of this is a user-initiated
editing operation which modifies the descendants or attributes of an editable
element. To prevent reentrancy when processing the backup element queue, each
custom element reactions stack also has a processing the backup element
queue flag, initially unset.
All elements have an associated custom element reaction queue, initially empty. Each item in the custom element reaction queue is of one of two types:
An upgrade reaction, which will upgrade the custom element and contains a custom element definition; or
A callback reaction, which will call a lifecycle callback, and contains a callback function as well as a list of arguments.
This is all summarized in the following schematic diagram:
To enqueue an element on the appropriate element queue, given an element element, run the following steps:
If the custom element reactions stack is empty, then:
Add element to the backup element queue.
If the processing the backup element queue flag is set, abort this algorithm.
Set the processing the backup element queue flag.
Queue a microtask to perform the following steps:
Invoke custom element reactions in the backup element queue.
Unset the processing the backup element queue flag.
Otherwise, add element to the current element queue.
To enqueue a custom element callback reaction, given a custom element element, a callback name callbackName, and a list of arguments args, run the following steps:
Let definition be element's custom element definition.
Let callback be the value of the entry in definition's lifecycle callbacks with key callbackName.
If callback is null, then abort these steps.
If callbackName is "attributeChangedCallback
", then:
Let attributeName be the first element of args.
If definition's observed attributes does not contain attributeName, then abort these steps.
Add a new callback reaction to element's custom element reaction queue, with callback function callback and arguments args.
Enqueue an element on the appropriate element queue given element.
To enqueue a custom element upgrade reaction, given an element element and custom element definition definition, run the following steps:
Add a new upgrade reaction to element's custom element reaction queue, with custom element definition definition.
Enqueue an element on the appropriate element queue given element.
To invoke custom element reactions in an element queue queue, run the following steps:
For each custom element element in queue:
Let reactions be element's custom element reaction queue.
Repeat until reactions is empty:
Remove the first element of reactions, and let reaction be that element. Switch on reaction's type:
If this throws any exception, then report the exception.
To ensure custom element reactions are
triggered appropriately, we introduce the [CEReactions]
IDL extended
attribute. It indicates that the relevant algorithm is to be supplemented with additional
steps in order to appropriately track and invoke custom element reactions.
The [CEReactions]
extended attribute must take no
arguments, and must not appear on anything other than an operation, attribute, setter, or deleter.
Additionally, it must not appear on readonly attributes.
Operations, attributes, setters, or deleters annotated with the [CEReactions]
extended attribute must run the following steps
surrounding the actions listed in the description of the operation, setter, deleter, or the
attribute's setter:
The intent behind this extended attribute is somewhat subtle. One way of accomplishing its goals would be to say that every operation, attribute, setter, and deleter on the platform must have these steps inserted, and to allow implementers to optimize away unnecessary cases (where no DOM mutation is possible that could cause custom element reactions to occur).
However, in practice this imprecision could lead to non-interoperable implementations of custom element reactions, as some implementations might forget to invoke these steps in some cases. Instead, we settled on the approach of explicitly annotating all relevant IDL constructs, as a way of ensuring interoperable behavior and helping implementations easily pinpoint all cases where these steps are necessary.
Any nonstandard APIs introduced by the user agent that could modify the DOM in such a way as to
cause enqueuing a custom element
callback reaction or enqueuing a
custom element upgrade reaction, for example by modifying any attributes or child elements,
must also be decorated with the [CEReactions]
attribute.
As of the time of this writing, the following nonstandard or not-yet-standardized APIs are known to fall into this category:
HTMLElement
's outerText
IDL attribute
HTMLInputElement
's webkitdirectory
and incremental
IDL attributes
HTMLLinkElement
's disabled
and scope
IDL attributes
ShadowRoot
's innerHTML
IDL attribute
The main content of a page — not including headers and footers, navigation links, sidebars, advertisements, and so forth — can be marked up in a variety of ways, depending on the needs of the author.
The simplest solution is to not mark up the main content at all, and just leave it as implicit.
Another way to think of this is that the body
elements marks up the main content of
the page, and the bits that aren't main content are excluded through the use of more appropriate
elements like aside
and nav
.
Here is a short Web page marked up along this minimalistic school of thought. The main content
is highlighted. Notice how all the other content in the body
is marked up
with elements to indicate that it's not part of the main content, in this case
header
, nav
, and footer
.
<!DOCTYPE HTML> <html lang="en"> <head> <title> My Toys </title> </head> <body> <header> <h1>My toys</h1> </header> <nav> <p><a href="/">Home</a></p> <p><a href="/contact">Contact</a></p> </nav> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> <footer> <p>© copyright 2010 by the boy</p> </footer> </body> </html>
If the main content is an independent unit of content that one could imagine syndicating
independently, then the article
element would be appropriate to mark up the main
content of the document.
The document in the previous example is here recast as a blog post:
<!DOCTYPE HTML> <html lang="en"> <head> <title> The Boy Blog: My Toys </title> </head> <body> <header> <h1>The Boy Blog</h1> </header> <nav> <p><a href="/">Home</a></p> <p><a href="/contact">Contact</a></p> </nav> <article> <header> <h1>My toys</h1> <p>Published August 4th</p> </header> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> </article> <footer> <p>© copyright 2010 by the boy</p> </footer> </body> </html>
If the main content is not an independent unit of content so much as a section of a larger
work, for instance a chapter, then the section
element would be appropriate to mark
up the main content of the document.
Here is the same document, but as a chapter in an online book:
<!DOCTYPE HTML> <html lang="en"> <head> <title> Chapter 2: My Toys — The Book of the Boy </title> </head> <body> <header> <hgroup> <h1>The Book of the Boy</h1> <h2>A book about boy stuff</h2> </hgroup> </header> <nav> <p><a href="/">Front Page</a></p> <p><a href="/toc">Table of Contents</a></p> <p><a href="/c1">Chapter 1</a> — <a href="/c3">Chapter 3</a></p> </nav> <section> <h1>Chapter 2: My Toys</h1> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> </section> </body> </html>
If neither article
nor section
would be appropriate, but the main
content still needs an explicit element, for example for styling purposes, then the
main
element can be used.
This is the same as the original example, but using main
for the main content
instead of leaving it implied:
<!DOCTYPE HTML> <html lang="en"> <head> <title> My Toys </title> <style> body > main { background: navy; color: yellow; } </style> </head> <body> <header> <h1>My toys</h1> </header> <nav> <p><a href="/">Home</a></p> <p><a href="/contact">Contact</a></p> </nav> <main> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> </main> <footer> <p>© copyright 2010 by the boy</p> </footer> </body> </html>
This specification does not provide a machine-readable way of describing bread-crumb navigation
menus. Authors are encouraged to just use a series of links in a paragraph. The nav
element can be used to mark the section containing these paragraphs as being navigation
blocks.
In the following example, the current page can be reached via two paths.
<nav> <p> <a href="/">Main</a> ▸ <a href="/products/">Products</a> ▸ <a href="/products/dishwashers/">Dishwashers</a> ▸ <a>Second hand</a> </p> <p> <a href="/">Main</a> ▸ <a href="/second-hand/">Second hand</a> ▸ <a>Dishwashers</a> </p> </nav>
This specification does not define any markup specifically for marking up lists
of keywords that apply to a group of pages (also known as tag clouds). In general, authors
are encouraged to either mark up such lists using ul
elements with explicit inline
counts that are then hidden and turned into a presentational effect using a style sheet, or to use
SVG.
Here, three tags are included in a short tag cloud:
<style> .tag-cloud > li > span { display: none; } .tag-cloud > li { display: inline; } .tag-cloud-1 { font-size: 0.7em; } .tag-cloud-2 { font-size: 0.9em; } .tag-cloud-3 { font-size: 1.1em; } .tag-cloud-4 { font-size: 1.3em; } .tag-cloud-5 { font-size: 1.5em; } @media speech { .tag-cloud > li > span { display:inline } } </style> ... <ul class="tag-cloud"> <li class="tag-cloud-4"><a title="28 instances" href="/t/apple">apple</a> <span>(popular)</span> <li class="tag-cloud-2"><a title="6 instances" href="/t/kiwi">kiwi</a> <span>(rare)</span> <li class="tag-cloud-5"><a title="41 instances" href="/t/pear">pear</a> <span>(very popular)</span> </ul>
The actual frequency of each tag is given using the title
attribute. A CSS style sheet is provided to convert the markup into a cloud of differently-sized
words, but for user agents that do not support CSS or are not visual, the markup contains
annotations like "(popular)" or "(rare)" to categorize the various tags by frequency, thus
enabling all users to benefit from the information.
The ul
element is used (rather than ol
) because the order is not
particularly important: while the list is in fact ordered alphabetically, it would convey the
same information if ordered by, say, the length of the tag.
The tag
rel
-keyword is
not used on these a
elements because they do not represent tags that apply
to the page itself; they are just part of an index listing the tags themselves.
This specification does not define a specific element for marking up conversations, meeting minutes, chat transcripts, dialogues in screenplays, instant message logs, and other situations where different players take turns in discourse.
Instead, authors are encouraged to mark up conversations using p
elements and
punctuation. Authors who need to mark the speaker for styling purposes are encouraged to use
span
or b
. Paragraphs with their text wrapped in the i
element can be used for marking up stage directions.
This example demonstrates this using an extract from Abbot and Costello's famous sketch, Who's on first:
<p> Costello: Look, you gotta first baseman? <p> Abbott: Certainly. <p> Costello: Who's playing first? <p> Abbott: That's right. <p> Costello becomes exasperated. <p> Costello: When you pay off the first baseman every month, who gets the money? <p> Abbott: Every dollar of it.
The following extract shows how an IM conversation log could be marked up, using the
data
element to provide Unix timestamps for each line. Note that the timestamps are
provided in a format that the time
element does not support, so the
data
element is used instead (namely, Unix time_t
timestamps).
Had the author wished to mark up the data using one of the date and time formats supported by the
time
element, that element could have been used instead of data
. This
could be advantageous as it would allow data analysis tools to detect the timestamps
unambiguously, without coordination with the page author.
<p> <data value="1319898155">14:22</data> <b>egof</b> I'm not that nerdy, I've only seen 30% of the star trek episodes <p> <data value="1319898192">14:23</data> <b>kaj</b> if you know what percentage of the star trek episodes you have seen, you are inarguably nerdy <p> <data value="1319898200">14:23</data> <b>egof</b> it's unarguably <p> <data value="1319898228">14:23</data> <i>* kaj blinks</i> <p> <data value="1319898260">14:24</data> <b>kaj</b> you are not helping your case
HTML does not have a good way to mark up graphs, so descriptions of interactive conversations
from games are more difficult to mark up. This example shows one possible convention using
dl
elements to list the possible responses at each point in the conversation.
Another option to consider is describing the conversation in the form of a DOT file, and
outputting the result as an SVG image to place in the document. [DOT]
<p> Next, you meet a fisher. You can say one of several greetings: <dl> <dt> "Hello there!" <dd> <p> She responds with "Hello, how may I help you?"; you can respond with: <dl> <dt> "I would like to buy a fish." <dd> <p> She sells you a fish and the conversation finishes. <dt> "Can I borrow your boat?" <dd> <p> She is surprised and asks "What are you offering in return?". <dl> <dt> "Five gold." (if you have enough) <dt> "Ten gold." (if you have enough) <dt> "Fifteen gold." (if you have enough) <dd> <p> She lends you her boat. The conversation ends. <dt> "A fish." (if you have one) <dt> "A newspaper." (if you have one) <dt> "A pebble." (if you have one) <dd> <p> "No thanks", she replies. Your conversation options at this point are the same as they were after asking to borrow her boat, minus any options you've suggested before. </dl> </dd> </dl> </dd> <dt> "Vote for me in the next election!" <dd> <p> She turns away. The conversation finishes. <dt> "Madam, are you aware that your fish are running away?" <dd> <p> She looks at you skeptically and says "Fish cannot run, miss". <dl> <dt> "You got me!" <dd> <p> The fisher sighs and the conversation ends. <dt> "Only kidding." <dd> <p> "Good one!" she retorts. Your conversation options at this point are the same as those following "Hello there!" above. <dt> "Oh, then what are they doing?" <dd> <p> She looks at her fish, giving you an opportunity to steal her boat, which you do. The conversation ends. </dl> </dd> </dl>
In some games, conversations are simpler: each character merely has a fixed set of lines that they say. In this example, a game FAQ/walkthrough lists some of the known possible responses for each character:
<section> <h1>Dialogue</h1> <p><small>Some characters repeat their lines in order each time you interact with them, others randomly pick from amongst their lines. Those who respond in order have numbered entries in the lists below.</small> <h2>The Shopkeeper</h2> <ul> <li>How may I help you? <li>Fresh apples! <li>A loaf of bread for madam? </ul> <h2>The pilot</h2> <p>Before the accident: <ul> <li>I'm about to fly out, sorry! <li>Sorry, I'm just waiting for flight clearance and then I'll be off! </ul> <p>After the accident: <ol> <li>I'm about to fly out, sorry! <li>Ok, I'm not leaving right now, my plane is being cleaned. <li>Ok, it's not being cleaned, it needs a minor repair first. <li>Ok, ok, stop bothering me! Truth is, I had a crash. </ol> <h2>Clan Leader</h2> <p>During the first clan meeting: <ul> <li>Hey, have you seen my daughter? I bet she's up to something nefarious again... <li>Nice weather we're having today, eh? <li>The name is Bailey, Jeff Bailey. How can I help you today? <li>A glass of water? Fresh from the well! </ul> <p>After the earthquake: <ol> <li>Everyone is safe in the shelter, we just have to put out the fire! <li>I'll go and tell the fire brigade, you keep hosing it down! </ol> </section>
HTML does not have a dedicated mechanism for marking up footnotes. Here are the suggested alternatives.
For short inline annotations, the title
attribute could be used.
In this example, two parts of a dialogue are annotated with footnote-like content using the
title
attribute.
<p> <b>Customer</b>: Hello! I wish to register a complaint. Hello. Miss? <p> <b>Shopkeeper</b>: <span title="Colloquial pronunciation of 'What do you'" >Watcha</span> mean, miss? <p> <b>Customer</b>: Uh, I'm sorry, I have a cold. I wish to make a complaint. <p> <b>Shopkeeper</b>: Sorry, <span title="This is, of course, a lie.">we're closing for lunch</span>.
Unfortunately, relying on the title
attribute is
currently discouraged as many user agents do not expose the attribute in an accessible manner as
required by this specification (e.g. requiring a pointing device such as a mouse to cause a
tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a
modern phone or tablet).
If the title
attribute is used, CSS can be used to
draw the reader's attention to the elements with the attribute.
For example, the following CSS places a dashed line below elements that have a title
attribute.
[title] { border-bottom: thin dashed; }
For longer annotations, the a
element should be used, pointing to an element later
in the document. The convention is that the contents of the link be a number in square
brackets.
In this example, a footnote in the dialogue links to a paragraph below the dialogue. The paragraph then reciprocally links back to the dialogue, allowing the user to return to the location of the footnote.
<p> Announcer: Number 16: The <i>hand</i>. <p> Interviewer: Good evening. I have with me in the studio tonight Mr Norman St John Polevaulter, who for the past few years has been contradicting people. Mr Polevaulter, why <em>do</em> you contradict people? <p> Norman: I don't. <sup><a href="#fn1" id="r1">[1]</a></sup> <p> Interviewer: You told me you did! ... <section> <p id="fn1"><a href="#r1">[1]</a> This is, naturally, a lie, but paradoxically if it were true he could not say so without contradicting the interviewer and thus making it false.</p> </section>
For side notes, longer annotations that apply to entire sections of the text rather than just
specific words or sentences, the aside
element should be used.
In this example, a sidebar is given after a dialogue, giving it some context.
<p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched. <p> <span class="speaker">Shopkeeper</span>: I'm sorry? <p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched. <p> <span class="speaker">Shopkeeper</span>: No no no, this's'a tobacconist's. <aside> <p>In 1970, the British Empire lay in ruins, and foreign nationalists frequented the streets — many of them Hungarians (not the streets — the foreign nationals). Sadly, Alexander Yalt has been publishing incompetently-written phrase books. </aside>
For figures or tables, footnotes can be included in the relevant figcaption
or
caption
element, or in surrounding prose.
In this example, a table has cells with footnotes that are given in prose. A
figure
element is used to give a single legend to the combination of the table and
its footnotes.
<figure> <figcaption>Table 1. Alternative activities for knights.</figcaption> <table> <tr> <th> Activity <th> Location <th> Cost <tr> <td> Dance <td> Wherever possible <td> £0<sup><a href="#fn1">1</a></sup> <tr> <td> Routines, chorus scenes<sup><a href="#fn2">2</a></sup> <td> Undisclosed <td> Undisclosed <tr> <td> Dining<sup><a href="#fn3">3</a></sup> <td> Camelot <td> Cost of ham, jam, and spam<sup><a href="#fn4">4</a></sup> </table> <p id="fn1">1. Assumed.</p> <p id="fn2">2. Footwork impeccable.</p> <p id="fn3">3. Quality described as "well".</p> <p id="fn4">4. A lot.</p> </figure>
An element is said to be actually disabled if it is one of the following:
button
element that is disabledinput
element that is disabledselect
element that is disabledtextarea
element that is disabledoptgroup
element that has a disabled
attributeoption
element that is disabledmenuitem
element that has a disabled
attributefieldset
element that is a disabled fieldsetThis definition is used to determine what elements can be focused and which elements match the :enabled
and :disabled
pseudo-classes.
The CSS Values and Units specification leaves the case-sensitivity of attribute names for the purpose of the 'attr()' function to be defined by the host language. [CSSVALUES]
When comparing the attribute name part of a CSS 'attr()' function to the names of namespace-less attributes on HTML elements in HTML documents, the name part of the CSS 'attr()' function must first be converted to ASCII lowercase. The same function when compared to other attributes must be compared according to its original case. In both cases, the comparison is case-sensitive.
This is the same as comparing the name part of a CSS attribute selector, specified in the next section.
The Selectors specification leaves the case-sensitivity of element names, attribute names, and attribute values to be defined by the host language. [SELECTORS]
Selectors defines that ID and class selectors, when matched against elements in documents that are in quirks mode, will be matched in an ASCII case-insensitive manner.
When comparing a CSS element type selector to the names of HTML elements in HTML documents, the CSS element type selector must first be converted to ASCII lowercase. The same selector when compared to other elements must be compared according to its original case. In both cases, the comparison is case-sensitive.
When comparing the name part of a CSS attribute selector to the names of namespace-less attributes on HTML elements in HTML documents, the name part of the CSS attribute selector must first be converted to ASCII lowercase. The same selector when compared to other attributes must be compared according to its original case. In both cases, the comparison is case-sensitive.
Attribute selectors on an HTML element in an HTML document must treat the values of attributes with the following names as ASCII case-insensitive, with one exception as noted in the rendering section:
accept
accept-charset
align
alink
axis
bgcolor
charset
checked
clear
codetype
color
compact
declare
defer
dir
direction
disabled
enctype
face
frame
hreflang
http-equiv
lang
language
link
media
method
multiple
nohref
noresize
noshade
nowrap
readonly
rel
rev
rules
scope
scrolling
selected
shape
target
text
type
(except as specified in the rendering section)
valign
valuetype
vlink
All other attribute values and everything else must be treated as entirely case-sensitive for the purposes of selector matching. This includes:
There are a number of dynamic selectors that can be used with HTML. This section defines when these selectors match HTML elements. [SELECTORS] [CSSUI]
:defined
The :defined
pseudo-class must match
any element that is defined.
:link
:visited
All a
elements that have an href
attribute, all area
elements that have an href
attribute, and all link
elements that have
an href
attribute, must match one of :link
and :visited
.
Other specifications might apply more specific rules regarding how these elements are to match these pseudo-classes, to mitigate some privacy concerns that apply with straightforward implementations of this requirement.
:active
The :active
pseudo-class is defined to
match an element
while an
element is being activated by the user
.
To determine whether a particular element is being activated for the purposes of
defining the :active
pseudo-class only, an
HTML user agent must use the first relevant entry in the following list.
:active
pseudo-classThe element is being activated.
label
element that is
currently matching :active
The element is being activated.
button
elementinput
element whose type
attribute is in the Submit Button, Image Button, Reset
Button, or Button stateThe element is being activated if it is in a formal activation state and it is not disabled.
For example, if the user is using a keyboard to push a button
element by pressing the space bar, the element would match this pseudo-class in
between the time that the element received the keydown
event and the time the element received the keyup
event.
menuitem
elementThe element is being activated if it is in a formal activation state
and it does not have a disabled
attribute.
a
element that has an href
attributearea
element that has an href
attributelink
element that has an href
attributeThe element is being activated if it is in a formal activation state.
The element is being activated.
An element is said to be in a formal activation state between the time the user begins to indicate an intent to trigger the element's activation behavior and either the time the user stops indicating an intent to trigger the element's activation behavior, or the time the element's activation behavior has finished running, which ever comes first.
An element is said to be being actively pointed at while the user indicates the element using a pointing device while that pointing device is in the "down" state (e.g. for a mouse, between the time the mouse button is pressed and the time it is depressed; for a finger in a multitouch environment, while the finger is touching the display surface).
:hover
The :hover
pseudo-class is defined to match
an element while the
user designates an element with a pointing device
. For the purposes of defining the
:hover
pseudo-class only, an HTML user agent
must consider an element as being one that the user designates if it is:
An element that the user indicates using a pointing device.
An element that has a descendant that the user indicates using a pointing device.
An element that is the labeled control of a label
element that is
currently matching :hover
.
Consider in particular a fragment such as:
<p> <label for=c> <input id=a> </label> <span id=b> <input id=c> </span> </p>
If the user designates the element with ID "a
" with their pointing
device, then the p
element (and all its ancestors not shown in the snippet above),
the label
element, the element with ID "a
", and the element
with ID "c
" will match the :hover
pseudo-class. The element with ID "a
" matches it from
condition 1, the label
and p
elements match it because of condition 2
(one of their descendants is designated), and the element with ID "c
"
matches it through condition 3 (its label
element matches :hover
). However, the element with ID "b
"
does not match :hover
: its descendant is not
designated, even though it matches :hover
.
:focus
For the purposes of the CSS :focus
pseudo-class, an element has the focus when its top-level browsing
context has the system focus, it is not itself a browsing context container,
and it is one of the elements listed in the focus chain of the currently focused area of the
top-level browsing context.
:target
For the purposes of the CSS :target
pseudo-class, the Document
's target elements are a list
containing the Document
's target element, if it is
not null, or containing no elements, if it is. [SELECTORS]
:enabled
The :enabled
pseudo-class must match any
button
, input
, select
, textarea
,
optgroup
, option
, menuitem
, or fieldset
element that is not actually disabled.
:disabled
The :disabled
pseudo-class must match
any element that is actually disabled.
:checked
The :checked
pseudo-class must match any
element falling into one of the following categories:
input
elements whose type
attribute is in
the Checkbox state and whose checkedness state is trueinput
elements whose type
attribute is in
the Radio Button state and whose checkedness state is trueoption
elements whose selectedness is truemenuitem
elements whose type
attribute
is in the Checkbox state and that have a
checked
attributemenuitem
elements whose type
attribute
is in the Radio state and that have a checked
attribute:indeterminate
The :indeterminate
pseudo-class
must match any element falling into one of the following categories:
input
elements whose type
attribute is in
the Checkbox state and whose indeterminate
IDL attribute is set to trueinput
elements whose type
attribute is in
the Radio Button state and whose radio button
group contains no input
elements whose checkedness state is true.progress
elements with no value
content attribute:default
The :default
pseudo-class must match any
element falling into one of the following categories:
button
elements that are their form's default buttoninput
elements whose type
attribute is in
the Submit Button or Image Button state, and that are their form's
default buttoninput
elements to which the checked
attribute applies and that have a checked
attributeoption
elements that have a selected
attribute:placeholder-shown
The :placeholder-shown
pseudo-class must match any element falling into one of the following
categories:
input
elements that have a placeholder
attribute whose value is currently being
presented to the user.textarea
elements that have a placeholder
attribute whose value is currently being
presented to the user.:valid
The :valid
pseudo-class must match any
element falling into one of the following categories:
form
elements that are not the form owner of any elements that
themselves are candidates for constraint
validation but do not satisfy their
constraintsfieldset
elements that have no descendant elements that themselves are candidates for constraint validation but do
not satisfy their constraints:invalid
The :invalid
pseudo-class must match any
element falling into one of the following categories:
form
elements that are the form owner of one or more elements
that themselves are candidates for constraint
validation but do not satisfy their
constraintsfieldset
elements that have of one or more descendant elements that themselves
are candidates for constraint
validation but do not satisfy their
constraints:in-range
The :in-range
pseudo-class must match
all elements that are candidates for
constraint validation, have range limitations, and that are neither
suffering from an underflow nor suffering from an overflow.
:out-of-range
The :out-of-range
pseudo-class must
match all elements that are candidates for
constraint validation, have range limitations, and that are either
suffering from an underflow or suffering from an overflow.
:required
The :required
pseudo-class must match
any element falling into one of the following categories:
:optional
The :optional
pseudo-class must match
any element falling into one of the following categories:
:read-only
:read-write
The :read-write
pseudo-class must
match any element falling into one of the following categories, which for the purposes of
Selectors are thus considered user-alterable: [SELECTORS]
input
elements to which the readonly
attribute applies, and that are mutable (i.e. that do not
have the readonly
attribute specified and that are not
disabled)textarea
elements that do not have a readonly
attribute, and that are not disabledinput
elements nor textarea
elementsThe :read-only
pseudo-class must match
all other HTML elements.
:dir(ltr)
The :dir(ltr)
pseudo-class must match all
elements whose directionality is 'ltr'.
:dir(rtl)
The :dir(rtl)
pseudo-class must match all
elements whose directionality is 'rtl'.
This specification does not define when an element matches the :lang()
dynamic pseudo-class, as it is defined in
sufficient detail in a language-agnostic fashion in the Selectors specification.
[SELECTORS]