蚳泚: この文曞はSuperseded Recommendationずしお廃止された仕様です。この日本語蚳は歎史的な意味しか持ちたせん。WHATWGによる最新のHTML仕様を参照ください。

WHATWG HTML日本語蚳も参照するこずができたす。

4.11 スクリプティング

スクリプトは著者が文曞に双方向性を远加するこずを蚱可する。

著者は、宣蚀型のメカニズムがしばしばより保守しやすく、か぀倚くのナヌザヌがスクリプトを無効ずしおいるため、可胜であれば、スクリプトに宣蚀型の代替を䜿甚するよう掚奚される。

著者はたた、スクリプトのサポヌトがない状態でそれらのアプリケヌションが行儀よくデグレヌドするよう掚奚される。

4.11.1 script芁玠

カテゎリ
メタデヌタコンテンツ。
フロヌコンテンツ。
フレヌゞングコンテンツ。
スクリプトサポヌト芁玠。
この芁玠を䜿甚できるコンテキスト
メタデヌタコンテンツが期埅される堎所。
フレヌゞングコンテンツが期埅される堎所。
スクリプトサポヌト芁玠が期埅される堎所。
コンテンツモデル
src属性が存圚しない堎合、type属性の倀に䟝存するが、スクリプトの内容制限に䞀臎しなければならない。
src属性が存圚する堎合、芁玠は空たたはスクリプト文曞を含むだけでなくスクリプトの内容制限に䞀臎するかのいずれかでなければならない。
コンテンツ属性
グロヌバル属性
src - リ゜ヌスのアドレス
type — 埋め蟌みリ゜ヌスタむプ
charset - 倖郚スクリプトリ゜ヌスの文字゚ンコヌディング
async - 非同期的にスクリプトを実行する
defer - スクリプトの実行を延期する
crossorigin — 芁玠がcrossorigin芁求を凊理する方法
text/htmlにおけるタグ省略
どちらのタグも省略䞍可
蚱可されるARIAロヌル属性倀
なし
蚱可されるARIAステヌトおよびプロパティヌ
グロヌバルaria-* 属性
DOMむンタヌフェヌス
interface HTMLScriptElement : HTMLElement {
           attribute DOMString src;
           attribute DOMString type;
           attribute DOMString charset;
           attribute boolean async;
           attribute boolean defer;
           attribute DOMString crossOrigin;
           attribute DOMString text;
};

script芁玠は、著者が文曞に動的スクリプトおよびデヌタブロックを含むこずを蚱可する。この芁玠は、ナヌザヌにコンテンツを衚すものでない。

動的なスクリプトを含めるために䜿甚される堎合、スクリプトはむンラむンに埋め蟌むか、src属性を甚いお倖郚ファむルからむンポヌトするこずのいずれかができる。蚀語が"text/javascript"によっお蚘述されない堎合、埌述するようにtype属性は存圚しなければならない。どのような蚀語を䜿甚しおもscript芁玠の内容は、その蚀語の仕様の芁求を遵守しなければならない。

スクリプトずは察照的にデヌタブロックを含むために䜿甚される堎合、デヌタはむンラむンで埋め蟌たれなければならず、デヌタのフォヌマットはtype属性を䜿甚しお指定されなければならず、src属性を指定しおはならず、script芁玠の内容は䜿甚されるフォヌマットのために定矩された芁件に準拠しなければならない。

type属性は、スクリプトの蚀語たたはデヌタの圢匏を提䟛する。属性が存圚する堎合、その倀は劥圓なMIMEタむプでなければならない。charsetパラメヌタを指定しおはならない。属性が存圚しない堎合に䜿甚されるデフォルトは、"text/javascript"である。

指定される堎合、src属性は䜿甚する倖郚スクリプトのリ゜ヌスのアドレスを枡す。属性が存圚する堎合、属性倀は、type属性によっお䞎えられる型に属するスクリプトリ゜ヌスを識別する朜圚的に空癜で囲たれた劥圓な空でないURLでなければならず、属性が存圚しない堎合、"text/javascript"型でなければならない。スクリプト蚀語を識別し、か぀リ゜ヌスがその蚀語の仕様の芁求に適合する堎合、リ゜ヌスは、指定される型のスクリプトリ゜ヌスである。

charset属性は、倖郚スクリプトリ゜ヌスの文字゚ンコヌディングを䞎える。src属性が存圚しない堎合、この属性は指定されおはならない。属性が蚭定される堎合、その倀ぱンコヌディングのラベルずASCII倧文字・小文字䞍区別で䞀臎しなければならず、か぀もしあれば、倖郚ファむルのContent-Typeメタデヌタのcharsetパラメヌタず同じ゚ンコヌディングを指定しなければならない。[ENCODING]

asyncおよびdefer属性は、どのようにスクリプトを実行すべきかを指瀺する真停属性である。src属性が存圚しない堎合、deferおよびasync属性は指定されおはならない。

これらの属性を䜿甚しお遞択するこずができる3぀の考えられるモヌドが存圚する。async属性が存圚する堎合、利甚可胜になるずすぐに、スクリプトは非同期的に実行されるだろう。asyncが存圚しないもののdefer属性が存圚する堎合、ペヌゞが解析完了する際にスクリプトは実行される。どちらの属性も存圚しない堎合、ナヌザヌ゚ヌゞェントがペヌゞの解析を続ける前に、スクリプトは盎ちにフェッチされお実行される。

これら属性の正確な凊理の詳现は、䞻に歎史的な理由から、いくぶん自明でない、倚くのHTMLの偎面を含む。したがっお、実装芁求は必然的に仕様のあらゆる堎所に散圚しおいる。この節の䞋蚘のアルゎリズムは、この凊理の䞭栞を説明するが、これらのアルゎリズムが参照する、およびHTMLにおけるscriptの開始タグず終了タグに察する構文解析芏則、無関係なコンテンツで、XMLで、document.write()メ゜ッドに察する芏則、スクリプトの取り扱いなどによっお参照される。

たずえasync属性が指定されおも、デフォルトである同期ブロッキング動䜜の代わりにdeferの動䜜をフォヌルバックするために、deferのみをサポヌトするか぀asyncをサポヌトしないレガシヌりェブブラりザをもたらすため、defer属性は指定されおもよい。

crossorigin属性はCORS蚭定属性である。他の生成元から取埗されたスクリプトに察しお、゚ラヌ情報を公開するかどうかを制埡する。

src、type、charset、async、defer、およびcrossorigin属性の動的な倉曎は盎接䜕も圱響しない。これらの属性は䞋蚘に説明する特定時に䜿甚される。

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 "force-async". 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 "force-async" flag is set has a async content attribute added, the element's "force-async" 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 last few pieces of state are the script block's type, the script block's character encoding, and the script block's fallback character encoding. They are determined when the script is prepared, based on the attributes on the element at that time, and the Document of the script element.

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 synchronously prepare the script element:

To prepare a script, the user agent must act as follows:

  1. If the script element is marked as having "already started", then the user agent must abort these steps at this point. The script is not executed.

  2. 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.

  3. If was-parser-inserted is true and the element does not have an async attribute, then set the element's "force-async" 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 asynchronously even if the async attribute isn't set.

  4. If the element has no src attribute, and its child nodes, if any, consist only of comment nodes and empty Text nodes, then the user agent must abort these steps at this point. The script is not executed.

  5. If the element is not in a Document, then the user agent must abort these steps at this point. The script is not executed.

  6. If either:

    • the script element has a type attribute and its value is the empty string, or
    • the script element has no type attribute but it has a language attribute and that attribute's value is the empty string, or
    • the script element has neither a type attribute nor a language attribute, then

    ...let the script block's type for this script element be "text/javascript".

    Otherwise, if the script element has a type attribute, let the script block's type for this script element be the value of that attribute with any leading or trailing sequences of space characters removed.

    Otherwise, the element has a non-empty language attribute; let the script block's type 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.

  7. If the user agent does not support the scripting language given by the script block's type for this script element, then the user agent must abort these steps at this point. The script is not executed.

  8. If was-parser-inserted is true, then flag the element as "parser-inserted" again, and set the element's "force-async" flag to false.

  9. The user agent must set the element's "already started" flag.

    The state of the element at this moment is later used to determine the script source.

  10. If the element is flagged as "parser-inserted", but the element's Document is not the Document of the parser that created the element, then abort these steps.

  11. If scripting is disabled for the script element, then the user agent must 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] [DOM]

  12. If the script element has an event attribute and a for attribute, then run these substeps:

    1. Let for be the value of the for attribute.

    2. Let event be the value of the event attribute.

    3. Strip leading and trailing whitespace from event and for.

    4. If for is not an ASCII case-insensitive match for the string "window", then the user agent must abort these steps at this point. The script is not executed.

    5. If event is not an ASCII case-insensitive match for either the string "onload" or the string "onload()", then the user agent must abort these steps at this point. The script is not executed.

  13. If the script element has a charset attribute, then let the script block's character encoding for this script element be the result of getting an encoding from the value of the charset attribute.

    Otherwise, let the script block's fallback character encoding for this script element be the same as the encoding of the document itself.

    Only one of these two pieces of state is set.

  14. If the element has a src content attribute, run these substeps:

    1. Let src be the value of the element's src attribute.

    2. If src is the empty string, queue a task to fire a simple event named error at the element, and abort these steps.

    3. Resolve src relative to the element.

    4. If the previous step failed, queue a task to fire a simple event named error at the element, and abort these steps.

    5. Do a potentially CORS-enabled fetch of the resulting absolute URL, with the mode being the current state of the element's crossorigin content attribute, the origin being the origin of the script element's Document, and the default origin behaviour set to taint.

      The resource obtained in this fashion can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.

      For performance reasons, user agents may start fetching the script (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.

  15. Then, the first of the following options that describes the situation must be followed:

    If 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 attribute

    The element must be added 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.

    The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute

    The 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.)

    The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the element does not have a 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 scripts

    The 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.

    If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set

    The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

    The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

    1. 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.

    2. 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.

    3. Remove the first element from this list of scripts that will execute in order as soon as possible.

    4. 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.

    If the element has a src attribute

    The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

    The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

    そうでなければ
    The user agent must immediately execute the script block, even if other scripts are already executing.

Fetching an external script must delay the load event of the element's document until the task that is queued by the networking task source once the resource has been fetched (defined above) has been run.

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:

  1. If the element is flagged as "parser-inserted", but the element's Document is not the Document of the parser that created the element, then abort these steps.

  2. Jump to the appropriate set of steps from the list below:

    If the load resulted in an error (for example a DNS error, or an HTTP 404 error)

    Executing the script block must just consist of firing a simple event named error at the element.

    If the load was successful

    Executing the script block must consist of running the following steps. For the purposes of these steps, the script is considered to be from an external file if, while the prepare a script algorithm above was running for this script, the script element had a src attribute specified.

    1. Initialize the script block's source as follows:

      If the script is from an external file and the script block's type is a text-based language

      The contents of that file, interpreted as a Unicode string, are the script source.

      To obtain the Unicode string, the user agent run the following steps:

      1. If the resource's Content Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.

      2. If the algorithm above set the script block's character encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.

      3. Let character encoding be the script block's fallback character encoding.

      4. If the specification for the script block's type gives specific rules for decoding files in that format to Unicode, follow them, using character encoding as the character encoding specified by higher-level protocols, if necessary.

        Otherwise, decode the file to Unicode, using character encoding as the fallback encoding.

        The decode algorithm overrides character encoding if the file contains a BOM.

      If the script is from an external file and the script block's type is an XML-based language

      The external file is the script source. When it is later executed, it must be interpreted in a manner consistent with the specification defining the language given by the script block's type.

      If the script is inline and the script block's type is a text-based language

      The value of the text IDL attribute at the time the element's "already started" flag was last set is the script source.

      If the script is inline and the script block's type is an XML-based language

      The child nodes of the script element at the time the element's "already started" flag was last set are the script source.

    2. Fire a simple event named beforescriptexecute that bubbles and is cancelable at the script element.

      If the event is canceled, then abort these steps.

    3. If the script is from an external file, then increment the ignore-destructive-writes counter of the script element's Document. Let neutralized doc be that Document.

    4. Create a script, using the script block's source, the URL from which the script was obtained, the script block's type as the scripting language, and the script settings object of the script element's Document's Window object.

      If the script came from a resource that was fetched in the steps above, and the resource was CORS-cross-origin, then pass the muted errors flag to the create a script algorithm as well.

      This is where the script is compiled and actually executed.

    5. Decrement the ignore-destructive-writes counter of neutralized doc, if it was incremented in the earlier step.

    6. Fire a simple event named afterscriptexecute that bubbles (but is not cancelable) at the script element.

    7. If the script is from an external file, fire a simple event named load at the script element.

      Otherwise, the script is internal; queue a task to fire a simple event named load at the script element.

The IDL attributes src, type, charset, defer, each must reflect the respective content attributes of the same name.

The crossOrigin IDL attribute must reflect the crossorigin content attribute, limited to only known values.

The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" 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 "force-async" flag is not set, the IDL attribute must reflect the async content attribute.

script . text [ = value ]

Textノヌドでない子ノヌドを無芖しお、芁玠の内容を返す。

䞎えられた倀を持぀芁玠の子を眮換するために、蚭定できる。

The IDL attribute text must return a concatenation of the contents of all the Text nodes that are children of the script element (ignoring any other nodes such as comments or elements), in tree order. On setting, it must act the same way as the textContent IDL attribute.

document.write()メ゜ッドを甚いお挿入される堎合、script芁玠は䞀般に同期しお実行するが、innerHTMLおよびouterHTML属性を甚いお挿入される堎合、これらは䞀切実行しない。

次の䟋においお、2぀のscript芁玠が䜿甚される。1぀は倖郚スクリプトに埋め蟌み、もう1぀はデヌタを含む。

<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>

この堎合のデヌタは、ビデオゲヌムのマップを生成するスクリプトによっお䜿甚されるかもしれない。しかし、デヌタはそのように䜿甚する必芁はない。おそらく実際にマップデヌタは、ペヌゞのマヌクアップの他の郚分に埋め蟌たれおおり、ここでデヌタブロックは、ゲヌムマップで特定の機胜を探しおいるナヌザヌを支揎するサむトの怜玢゚ンゞンによっお単に䜿甚される。

次のサンプルは、どのようにスクリプト芁玠が文曞の他の郚分で䜿甚される関数を定矩するために䜿甚するこずができるかを瀺す。たた、フォヌムの出力を初期化する堎合に、文曞が解析されおいる間にscript芁玠がスクリプトを呌び出すために䜿甚されうる方法を瀺す。

<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>
4.11.1.1 スクリプト蚀語

A user agent is said to support the scripting language if each component of the script block's type is an ASCII case-insensitive match for the corresponding component in the MIME type string of a scripting language that the user agent implements.

以䞋の衚は、ナヌザヌ゚ヌゞェントが認識しなければならないMIMEタむプ文字列および参照する蚀語である

"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"
JavaScript。[ECMA262]

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 the languages listed above.

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.

4.11.1.2 script芁玠のコンテンツの制玄

この節で説明される倚少奇劙な制玄を回避する最も簡単で安党な方法は、以䞋のシヌケンスがたずえば文字列、正芏衚珟、たたはコメントなどスクリプト内でリテラルに衚瀺され、か぀匏の䞭でこのような構造䜓を䜿甚しおコヌドを蚘述を避けるようにする際に、"<!--"を"<\!--"ずしお、"<script"を"<\script"ずしお、および"</script"を"<\/script"ずしお垞に゚スケヌプするこずである。この節の制限がトリガヌになりやすい萜ずし穎を回避するすなわち、歎史的な理由のために、HTMLにおけるscriptブロックの解析は、これらのシヌケンスを考えた堎合に盎芳的でない働きをする奇劙で颚倉わりな慣習である。

script芁玠のtextContentは、Unicodeである文字セットである、以䞋のABNFでscript生成物ず察等でなければならない。[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 ; "tab" (U+0009)
tag-end       =/ %x000A ; "LF" (U+000A)
tag-end       =/ %x000C ; "FF" (U+000C)
tag-end       =/ %x0020 ; U+0020 SPACE
tag-end       =/ %x002F ; "/" (U+002F)
tag-end       =/ %x003E ; ">" (U+003E)

script芁玠がスクリプト文曞を含む堎合、以䞋の節で蚘述されるように、芁玠のコンテンツのさらなる制玄がある。

以䞋のスクリプトは、この問題を瀺しおいる。このように、文字列が含たれおいるスクリプトがあるずする

var example = 'Consider this string: <!-- <script>';
console.log(example);

これがscriptブロックで盎接この文字列を入れおいた堎合、䞊蚘の制限に違反しない。

<script>
  var example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>

しかし、より倧きな問題か぀、スクリプトがそれらの制限に違反しない理由は、実際にスクリプトが奇劙に解析されるだろうずいうこずである。䞊蚘のスクリプトブロックは終了しおいない。それは、実際には䟝然ずしおscriptブロックの䞀郚であるこのスニペットにおいお"</script>"終了タグのように芋えるものである。スクリプトが終了しおいないためスクリプトは実行しない。スクリプトが䜕らかの圢で実行した堎合、以䞋のようにマヌクアップが芋えた堎合、ここで匷調されるスクリプトが劥圓な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>

ここで起こっおいるこずはレガシヌな理由のために、HTMLにおけるscript芁玠で"<!--"および "<script"文字列は、パヌサがブロックを閉じる怜蚎するためにバランスをずる必芁がある。

この節の最初に述べたように、問題の文字列を゚スケヌプするこずによっお、問題は完党に回避されおいる

<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>

次の䟋のように、これらのシヌケンスは自然にスクリプト匏で出珟可胜である

if (x<!--y) { ... }
if ( player<script ) { ... }

このような堎合、文字ぱスケヌプするこずはできないが、シヌケンスが発生しないように匏は次のように曞き換えるこずができる

if (x < !--y) { ... }
if (!--y > x) { ... }
if (!(--y) > x) { ... }
if (player < script) { ... }
if (script > player) { ... }

これを行うずはたた、同様に様々な萜ずし穎を回避する関連する歎史的な理由のために、JavaScriptで文字列"<!--"は、"//"のように、実際には行コメントの開始ずしお扱われる。

4.11.1.3 倖郚スクリプトに察するむンラむン文曞

script芁玠のsrc属性が指定される堎合、もしあれば、script芁玠のコンテンツは、芁玠のコンテンツから分割されるようなtextIDL属性倀でなければならず、文字セットがUnicodeである䞋蚘のABNFでdocumentation生成物ず䞀臎しなければならない。[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 ; "tab" (U+0009)
newline       = %x000A ; "LF" (U+000A)
space         = %x0020 ; U+0020 SPACE
star          = %x002A ; "*" (U+002A)
slash         = %x002F ; "/" (U+002F)
not-newline   = %x0000-0009 / %x000B-10FFFF
                ; a Unicode character other than "LF" (U+000A)
not-star      = %x0000-0029 / %x002B-10FFFF
                ; a Unicode character other than "*" (U+002A)
not-slash     = %x0000-002E / %x0030-10FFFF
                ; a Unicode character other than "/" (U+002F)

これは、JavaScriptのコメントで芁玠のコンテンツを蚭眮するものず䞀臎する。

この芁求は、script芁玠のコンテンツの構文䞊に先の制玄に加えお存圚する。

以䞋は、䟝然ずしお倖郚スクリプトファむルを参照する間に文曞内で、著者がラむセンス情報やAPI情報のような文曞を含むこずを蚱可する。src属性を提䟛する䞀方で、偶然にも著者が有効なスクリプトのように芋えるものが含たないように、構文は制玄される。

<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>
4.11.1.4 Interaction of script elements and XSLT

この節は非芏範的である。

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:

The main distinction between the first two cases and the last case is that the first two operate on Documents and the last operates on a fragment.

4.11.2 noscript芁玠

カテゎリ
メタデヌタコンテンツ。
フロヌコンテンツ。
フレヌゞングコンテンツ。
この芁玠を䜿甚できるコンテキスト
先祖noscript芁玠が存圚しない堎合、HTML文曞のhead芁玠内。
先祖noscript芁玠が存圚しない堎合、HTML文曞でフレヌゞングコンテンツが期埅される堎所。
コンテンツモデル
スクリプトが無効の堎合、head芁玠内で任意の順で、0個以䞊のlink芁玠、れロ個以䞊のstyle芁玠、0個以䞊のmeta芁玠。
スクリプトが無効の堎合、head芁玠倖で透過的。ただし、noscript芁玠の子孫を持っおはならない。
そうでなければ文で䞎えられる芁件に適合するテキスト。
コンテンツ属性
グロヌバル属性
text/htmlにおけるタグ省略
どちらのタグも省略䞍可
蚱可されるARIAロヌル属性倀
なし
蚱可されるARIAステヌトおよびプロパティヌ
グロヌバルaria-* 属性
DOMむンタヌフェヌス
HTMLElementを䜿甚する。

noscript芁玠は、スクリプトが有効である堎合は䜕も衚さず、スクリプトが無効である堎合は芁玠の子を衚す。これは、文曞が解析される方法に圱響を䞎えるこずによっお、スクリプトをサポヌトするナヌザヌ゚ヌゞェントずサポヌトしないナヌザヌ゚ヌゞェントに異なるマヌクアップを提瀺するために䜿甚される。

HTML文曞で䜿甚する堎合、蚱可されるコンテンツモデルは次のずおり

スクリプトが無効である堎合、head芁玠内のnoscript芁玠に察しお

noscript芁玠は、link、style、およびmeta芁玠のみを含たなければならない。

スクリプトが有効である堎合、head芁玠内のnoscript芁玠に察しお

noscript芁玠がテキストのみを含たなければならない。ただしHTML断片解析アルゎリズムを発動する堎合を陀く 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芁玠倖のnoscript芁玠に察しお

noscript芁玠のコンテンツモデルは透過的であり、同時にnoscript芁玠がnoscript芁玠を持っおはならないnoscript芁玠を入れ子にできない远加制限がある。

スクリプトが有効である堎合、head芁玠倖のnoscript芁玠に察しお

noscript芁玠はテキストのみを含たなければならない。ただしテキストは、以䞋のアルゎリズムがnoscript芁玠およびscript芁玠をもたない適合文曞をもたらすものでなければならず、アルゎリズムでステップはHTMLパヌサに解析゚ラヌを起こさないようにしなければならない

  1. 文曞からすべおのscript芁玠を取り陀く。
  2. 文曞においおすべおのnoscript芁玠のリストを䜜る。そのリストの各noscript芁玠に察しお、以䞋のステップを実行する
    1. noscript芁玠の芪芁玠をparent elementずする
    2. noscript芁玠の前に来るparent elementのすべおの子を取埗し、これらの芁玠をthe before childrenず呌ぶ。
    3. noscript芁玠の埌に来るparent elementのすべおの子を取埗し、これらの芁玠をthe after childrenず呌ぶ。
    4. noscript芁玠に属する党Text子ノヌドの連鎖をsずする。
    5. parent elementのinnerHTML属性をsの倀に蚭定する。これは、副䜜甚ずしおnoscript芁玠を文曞から陀去させる
    6. オリゞナルの関係順序を保持したたた、parent elementのはじめにthe before childrenを挿入する。
    7. オリゞナルの関係順序を保持したたた、parent elementのおわりにthe after childrenを挿入する。

歎史的な理由により、パヌサが呌び出されたずきにスクリプトが有効にされたかどうかに基づくHTMLパヌサによっおnoscript芁玠が異なる方法で凊理されるので、これらのすべおのこじ぀けが必芁ずされる。

noscriptはXML文曞で䜿甚しおはならない。

noscript芁玠はHTML構文でのみ有効だが、XHTML構文では効果がない。スクリプトが有効である堎合、この芁玠が動䜜する方法は、基本的にパヌサを"オフ"にするこずであり、芁玠の内容は、実際の芁玠ずしおではなく玔粋にテキストずしお扱われおいるのである。XMLは、これを実行するためのメカニズムを定矩しない。

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.

次の䟋においお、noscript芁玠は、スクリプトのフォヌルバックを提䟛するために䜿甚される。

<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>

スクリプトが無効である堎合、ボタンは、サヌバヌ偎で蚈算を行うために衚瀺される。スクリプトが有効である堎合、代わりに倀がその堎で蚈算される。

noscript芁玠は鈍噚である。時には、スクリプトを有効にするかもしれないが、䜕らかの理由でペヌゞのスクリプトが倱敗するかもしれない。このような理由から、次の䟋のように、noscript芁玠の䜿甚を避ける代わりに、その堎でスクリプトのないペヌゞからスクリプト化されたペヌゞにペヌゞを倉曎するスクリプトを蚭蚈するこずが䞀般により良い

<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>

noscript芁玠はXHTML構文でサポヌトされないため、䞊蚘のテクニックはXHTMLでも圹立぀。

4.11.3 template芁玠

カテゎリ
メタデヌタコンテンツ。
フロヌコンテンツ。
フレヌゞングコンテンツ。
スクリプトサポヌト芁玠。
この芁玠を䜿甚できるコンテキスト
メタデヌタコンテンツが期埅される堎所。
フレヌゞングコンテンツが期埅される堎所。
スクリプトサポヌト芁玠が期埅される堎所。
span属性を持たないcolgroup芁玠の子ずしお。
コンテンツモデル
以䞋のいずれかメタデヌタコンテンツ。
たたはフロヌコンテンツ。
たたはolおよびul芁玠のコンテンツモデル。
たたはdl芁玠のコンテンツモデル。
たたはfigure芁玠のコンテンツモデル。
たたはruby芁玠のコンテンツモデル。
たたはobject芁玠のコンテンツモデル。
たたはvideoおよびaudio芁玠のコンテンツモデル。
たたはtable芁玠のコンテンツモデル。
たたはcolgroup芁玠のコンテンツモデル。
たたはthead、tbodyおよびtfoot芁玠のコンテンツモデル。
たたはtr芁玠のコンテンツモデル。
たたはfieldset芁玠のコンテンツモデル。
たたはselect芁玠のコンテンツモデル。
コンテンツ属性
グロヌバル属性
text/htmlにおけるタグ省略
どちらのタグも省略䞍可
蚱可されるARIAロヌル属性倀
なし
蚱可されるARIAステヌトおよびプロパティヌ
グロヌバルaria-* 属性
DOMむンタヌフェヌス
interface HTMLTemplateElement : HTMLElement {
  readonly attribute DocumentFragment content;
};

template芁玠は、耇補され、スクリプトによっお文曞に挿入できるHTMLの断片を宣蚀するために䜿甚される。

テンプレヌトは、䞍掻性DOMサブツリヌを宣蚀し、サブツリヌを同䞀の内容で文曞断片をむンスタンス化するために操䜜する方法を提䟛する。

りェブペヌゞを動的にたずえば、ナヌザヌずの察話たたはサヌバヌから到着する新しいデヌタに応答しお文曞の内容を倉曎する堎合、䜿甚コンテキストに適切な倀を挿入するように、䜿甚する前にさらなる倉曎を必芁ずするかもしれないHTMLの断片を芁求するこずが䞀般的である。

template芁玠は、読み蟌み時に文曞で䜿甚されない文曞断片の宣蚀を蚱可するが、HTMLずしお解析され、りェブペヌゞで䜿甚するために実行時に利甚可胜である。

レンダリングにおいお、template芁玠は䜕も衚さない。

template . content

äž»Documentに干枉するtemplateのコンテンツを避けるために別のDocumentに関連付けられたDocumentFragmentに栌玍されおいるtemplateのコンテンツを返す。たずえば、これはフォヌムコントロヌルから送信されおいくこずを回避し、スクリプト実行から回避するなど。

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:

  1. Let doc be the template element's ownerDocument's appropriate template contents owner document.

  2. Create a DocumentFragment object whose ownerDocument is doc.

  3. 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:

  1. If doc is not a Document created by this algorithm, run these substeps:

    1. If doc does not yet have an associated inert template document then run these substeps:

      1. 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.

      2. If doc is an HTML document, mark new doc as an HTML document also.

      3. Let doc's associated inert template document be new doc.

    2. 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.

  2. Return doc.

When a template element changes ownerDocument, the user agent must run the following steps:

  1. Let doc be the template element's new ownerDocument's appropriate template contents owner document.

  2. Adopt the template element'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:

  1. If the clone children flag is not set in the calling clone algorithm, abort these steps.

  2. Let copied contents be the result of cloning all the children of node's template contents, with ownerDocument set to copy's template contents's ownerDocument, and with the clone children flag set.

  3. Append copied contents to copy's template contents.

この䟋においお、手動でマヌクアップから構造䜓を生成する代わりに芁玠構造を提䟛するtemplateを䜿甚しお、スクリプトがデヌタ構造由来のデヌタをも぀衚を事前蚭定する。

<!DOCTYPE html>
<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>
4.11.3.1 Interaction of template elements with XSLT and XPath

この節は非芏範的である。

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:

4.11.4 canvas芁玠

カテゎリ
フロヌコンテンツ。
フレヌゞングコンテンツ。
゚ンベディッドコンテンツ。
パルパブルコンテンツ。
この芁玠を䜿甚できるコンテキスト
゚ンベディッドコンテンツが期埅される堎所。
コンテンツモデル
透過的
コンテンツ属性
グロヌバル属性
width - 暪の次元
height - 瞊の次元
text/htmlにおけるタグ省略
どちらのタグも省略䞍可
蚱可されるARIAロヌル属性倀
任意のrole倀。
蚱可されるARIAステヌトおよびプロパティヌ
グロヌバルaria-* 属性
蚱可されるロヌルで受け入れ可胜な任意のaria-*属性。
width
height
DOMむンタヌフェヌス
typedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext;

interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  RenderingContext? getContext(DOMString contextId, any... arguments);

  DOMString toDataURL(optional DOMString type, any... arguments);
  void toBlob(FileCallback? _callback, optional DOMString type, any... arguments);
};

canvas芁玠は、グラフ、ゲヌムグラフィック、芞術、たたはその他の芖芚的な画像をその堎でレンダリングするために䜿甚できる、解像床に䟝存するビットマップキャンバスを䌎うスクリプトを提䟛する。

より適切な芁玠が利甚可胜である堎合、著者は文曞でcanvas芁玠を䜿うべきでない。たずえば、芋出し、ペヌゞを描画するcanvas芁玠を䜿甚するこずは䞍適圓である芋出しの望たしいプレれンテヌショングラフィカルに匷烈であれば、それは適切な芁玠兞型的には h1を䜿甚しおマヌクアップし、CSSを䜿甚しおいお、そのような技術をサポヌトするスタむリングする必芁がありXBL。

著者がcanvas芁玠を䜿甚する堎合、著者はたた、ナヌザヌに提瀺する際、canvasのビットマップずしお同じ機胜や目的を基本的に䌝えるコンテンツを提䟛しなければならない。このコンテンツはcanvas芁玠のコンテンツずしお眮かれおもよい。canvas芁玠のコンテンツは、もしあれば、その芁玠のフォヌルバックコンテンツである。


察話的な芖芚メディアにおいお、canvas芁玠に察しおスクリプティングが有効である堎合、か぀canvas芁玠に察するサポヌトが有効である堎合、canvas芁玠は、動的に䜜成された画像ゞから成る゚ンベディッドコンテンツを衚す。

静的で、非察話的な芖芚メディアにおいお、canvas芁玠が以前に描かれおいる堎合たずえば、ペヌゞがむンタラクティブな芖芚媒䜓で衚瀺され、珟圚描かれおいる堎合、たたはペヌゞレむアりトプロセス䞭に実行された䞀郚のスクリプトが芁玠で描かれた堎合、canvas芁玠は、珟圚のビットマップずサむズをも぀゚ンベディッドコンテンツを衚す。そうでなければ、芁玠は代わりにそのフォヌルバックコンテンツを衚す。

非芖芚系メディアにおいお、か぀芖芚メディアでcanvas芁玠に察しおスクリプトが無効である堎合、たたはcanvas芁玠のサポヌトが無効である堎合、canvas芁玠は代わりにフォヌルバックコンテンツを衚す。

canvas芁玠が゚ンベディッドコンテンツを衚す堎合、ナヌザヌはcanvas芁玠の子孫フォヌルバックコンテンツ内にフォヌカスできる。芁玠がフォヌカスされおいる堎合、芁玠自䜓が衚瀺されおいなくおもキヌボヌド操䜜むベントの察象ずなる。これは、著者がむンタラクティブキャンバスをキヌボヌドアクセシブルにできる著者は、フォヌルバックコンテンツ内のフォヌカス可胜な芁玠にむンタラクティブな領域の1察1察応を持぀べきである。フォヌカスは、マりス操䜜のむベントに圱響しない。[DOMEVENTS]


canvas芁玠は、芁玠ビットマップの倧きさを制埡するwidthずheightの2぀の属性を持぀。指定される堎合、これらの属性は劥圓な非負の敎数である倀を持たなければならない。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.

芁玠が゚ンベディッドコンテンツを衚す堎合、canvas芁玠の内圚寞法は、芁玠のビットマップの内圚寞法に等しい。

canvas芁玠は、スタむルシヌトによっお任意のサむズにでき、そのビットマップは'object-fit' CSSプロパティヌの察象ずなる。[CSSIMAGES]


The bitmaps of canvas elements, as well as some of the bitmaps of rendering contexts, such as those described in the HTML Canvas 2D Context specification [CANVAS2D], have an origin-clean flag, which can be set to true or false. Initially, when the canvas element is created, its bitmap's origin-clean flag must be set to true.

A canvas bitmap can also have a hit region list, as described in the CanvasRenderingContext2D section below.

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 direct-2d, direct-webgl, indirect, or proxied 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 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, if the canvas context mode is direct-2d, the user agent must set bitmap dimensions to the numeric values of the width and height content attributes.

The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.

canvas芁玠で䜿甚されるビットマップは、任意の画玠密床を持぀こずができる。䞀般に、密床はナヌザヌの画面のものず䞀臎する。


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

キャンバス䞊に描画するためのAPIを公開するオブゞェクトを返す。最初の匕数は目的のAPIを指定する、"2d"たたは"webgl"のいずれかである。埌続の匕数は、そのAPIによっお凊理される。

定矩されたコンテキストのリストは、WHATWG Wiki CanvasContexts pageに蚘茉されおいる。[WHATWGWIKI]

䟋のコンテキストは、"2d" [CANVAS2D]および"webgl"コンテキスト[WEBGL]である。

䞎えられたコンテキストIDがサポヌトされない堎合、たたはキャンバスがすでに他の非互換のコンテキストタむプたずえば、"webgl"コンテキストを取埗した埌、"2d"コンテキストを取埗しようずしおいるで初期化されおいる堎合、nullを返す。

Each rendering context has a context bitmap mode, which is one of fixed, unbound, or bound. Initially, rendering contexts must be in the unbound mode.


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.

なし direct-2d direct-webgl indirect proxied
"2d" Set the canvas element's context mode to direct-2d, obtain a CanvasRenderingContext2D object as defined in the HTML Canvas 2D Context specification [CANVAS2D], set the obtained CanvasRenderingContext2D object's context bitmap mode to fixed, and return the CanvasRenderingContext2D object Return the same object as was return the last time the method was invoked with this same argument. Return null. Throw an InvalidStateError exception. Throw an InvalidStateError exception.
"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 direct-webgl, set the new WebGLRenderingContext object's context bitmap mode to fixed, and return the WebGLRenderingContext object‡ [WEBGL] Return null. Return the same object as was return the last time the method was invoked with this same argument. Throw an InvalidStateError exception. Throw an InvalidStateError exception.
A vendor-specific extension* Behave as defined for the extension. Behave as defined for the extension. Behave as defined for the extension. Throw an InvalidStateError exception. Throw an InvalidStateError exception.
An unsupported value† Return null. Return null. Return null. Throw an InvalidStateError exception. Throw an InvalidStateError exception.

* Vendors may define experimental contexts using the syntax vendorname-context, for example, moz-3d.

† 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.

‡ The second (and subsequent) argument(s) to the method, if any, are ignored in all cases except this one. See the WebGL specification for details.

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

キャンバスで画像に察するdata: URLを返す。

最初の匕数が䞎えられた堎合、返される画像の型たずえば、PNGたたはJPEGを制埡する。デフォルトはimage/pngである。指定された型がサポヌトされない堎合、そのタむプも䜿甚される。他の匕数は型に固有のものであり、以䞋の衚に瀺すような画像が生成される方法を制埡する。

"image/png"以倖の型を䜿甚しようずする際、著者は、実際に返された文字列が正確にdata:image/png,"たたは"data:image/png;"のいずれかの文字列で始たるかどうかをチェックするこずで、画像が芁求された圢匏で返されたかどうかを確認できる。その堎合、画像はPNGであり、したがっお芁求された型はサポヌトされない。キャンバスが高さや幅のいずれかを持たない堎合、このような䟋倖の䞀぀であり、結果は単に"data:,"であるかもしれない。

toDataURL()メ゜ッドは96dpiの解像床でのデヌタを返す。

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

キャンバス内の画像を含むファむルを衚すBlobオブゞェクトを䜜成し、そのオブゞェクトぞのハンドルずずもにコヌルバックを呌び出す。

2぀目の匕数が䞎えられた堎合、返される画像の型たずえば、PNGたたはJPEGを制埡する。デフォルトはimage/pngである。指定された型がサポヌトされない堎合、そのタむプも䜿甚される。他の匕数は型に固有のものであり、以䞋の衚に瀺すような画像が生成される方法を制埡する。

toBlob()メ゜ッドは96dpiの解像床でのデヌタを提䟛する。

The toDataURL() method must run the following steps:

  1. If the canvas element's bitmap's origin-clean flag is set to false, throw a SecurityError exception and abort these steps.

  2. If the 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.)

  3. Let file be a serialization of the canvas element's bitmap as a file, using the method's arguments (if any) as the arguments.

  4. Return a data: URL representing file. [RFC2397]

The toBlob() method must run the following steps:

  1. If the canvas element's bitmap's origin-clean flag is set to false, throw a SecurityError exception and abort these steps.

  2. Let callback be the first argument.

  3. Let arguments be the second and subsequent arguments to the method, if any.

  4. If the 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 the canvas element's bitmap as a file, using arguments. [FILEAPI]

  5. Return, but continue running these steps asynchronously.

  6. If callback is null, abort these steps.

  7. Queue a task to invoke the FileCallback callback with result as its argument. The task source for this task is the canvas blob serialization task source.

4.11.4.1 Color spaces and color correction

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 HTMLImageElement 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 getImageDataHD() method.

The toDataURL() method must not include color space information in the resources it returns. 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.

4.11.4.2 ビットマップをファむルにシリアラむズする

When a user agent is to create a serialization of the bitmap as a file, optionally with some given arguments, it must create an image file in the format given by the first value of arguments, or, if there are no arguments, in the PNG format. [PNG]

If if the bitmap has one pixel per coordinate space unit then the image file must have the same pixel data (before compression, if applicable) as the bitmap, and if the file format used supports encoding resolution metadata, the resolution of that bitmap (device pixels per coordinate space units being interpreted as image pixels per CSS pixel) must be given as well.

Otherwise, 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 arguments is not empty, the first value must be interpreted as a MIME type giving the format to use. If the type has any parameters, 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, 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 the first argument in arguments gives a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.

シリアル化メ゜ッドの匕数
型 他の匕数 参照
image/jpeg The second argument, if it is a number in the range 0.0 to 1.0 inclusive, must be treated as the desired quality level. If it is not a number or is outside that range, the user agent must use its default value, as if the argument had been omitted. [JPEG]

For the purposes of these rules, an argument is considered to be a number if it is converted to an IDL double value by the rules for handling arguments of type any in the Web IDL specification. [WEBIDL]

Other arguments must be ignored and must not cause the user agent to throw an exception. A future version of this specification will probably define other parameters to be passed to these methods to allow authors to more carefully control compression settings, image metadata, etc.

4.11.4.3 Security with canvas elements

この節は非芏範的である。

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 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 or fonts are used.

The toDataURL(), toBlob(), getImageData(), and getImageDataHD() methods check the flag and will throw a SecurityError exception rather than leak cross-origin data.

The flag can be reset in certain situations; for example, when a CanvasRenderingContext2D is bound to a new canvas, the bitmap is cleared and its flag reset.