1. 8.10 画像
      1. 8.10.1 The ImageData interface
      2. 8.10.2 The ImageBitmap interface
    2. 8.11 アニメーションフレーム

8.10 画像

8.10.1 The ImageData interface

An ImageData object represents a rectanglar bitmap with width equal to the width attribute and height equal to the height attribute. The pixel values of this bitmap are stored in the data attribute in left-to-right order, row by row from top to bottom, starting with 0 for the top left pixel, with the order and numerical representation of the color components of each pixel determined by the pixelFormat attribute. The color space of the pixel values of the bitmap is determined by the colorSpace attribute.

imageData = new ImageData(sw, sh [, settings])

Returns an ImageData object with the given dimensions and the color space indicated by settings. All the pixels in the returned object are transparent black.

Throws an "IndexSizeError" DOMException if either of the width or height arguments are zero.

imageData = new ImageData(data, sw [, sh [, settings ] ])

Returns an ImageData object using the data provided in the ImageDataArray argument, interpreted using the given dimensions and the color space indicated by settings.

The byte length of the data needs to be a multiple of the number of bytes per pixel times the given width. If the height is provided as well, then the length needs to be exactly the number of bytes per pixel times the width times the height.

Throws an "IndexSizeError" DOMException if the given data and dimensions can't be interpreted consistently, or if either dimension is zero.

imageData.width
imageData.height

Returns the actual dimensions of the data in the ImageData object, in pixels.

imageData.data

Returns the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.

imageData.colorSpace

ImageData/colorSpace

FirefoxNoSafari15.2+Chrome92+
Opera?Edge92+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the color space of the pixels.

The new ImageData(sw, sh, settings) constructor steps are:

  1. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException.

  2. Initialize this given sw, sh, and settings.

  3. Initialize the image data of this to transparent black.

The new ImageData(data, sw, sh, settings) constructor steps are:

  1. Let bytesPerPixel be 4 if settings["pixelFormat"] is "rgba-unorm8"; otherwise 8.

  2. Let length be the buffer source byte length of data.

  3. If length is not a nonzero integral multiple of bytesPerPixel, then throw an "InvalidStateError" DOMException.

  4. Let length be length divided by bytesPerPixel.

  5. If length is not an integral multiple of sw, then throw an "IndexSizeError" DOMException.

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

  6. Let height be length divided by sw.

  7. If sh was given and its value is not equal to height, then throw an "IndexSizeError" DOMException.

  8. Initialize this given sw, sh, settings, and source set to data.

    This step does not set this's data to a copy of data. It sets it to the actual ImageDataArray object passed as data.

To initialize an ImageData object imageData, given a positive integer number of pixels per row pixelsPerRow, a positive integer number of rows rows, an ImageDataSettings settings, an optional ImageDataArray source, and an optional PredefinedColorSpace defaultColorSpace:

  1. If source was given:

    1. If settings["pixelFormat"] equals "rgba-unorm8" and source is not a Uint8ClampedArray, then throw an "InvalidStateError" DOMException.

    2. If settings["pixelFormat"] is "rgba-float16" and source is not a Float16Array, then throw an "InvalidStateError" DOMException.

    3. Initialize the data attribute of imageData to source.

  2. Otherwise (source was not given):

    1. If settings["pixelFormat"] is "rgba-unorm8", then initialize the data attribute of imageData to a new Uint8ClampedArray object. The Uint8ClampedArray object must use a new ArrayBuffer for its storage, and must have a zero byte offset and byte length equal to the length of its storage, in bytes. The storage ArrayBuffer must have a length of 4 × rows × pixelsPerRow bytes.

    2. Otherwise, if settings["pixelFormat"] is "rgba-float16", then initialize the data attribute of imageData to a new Float16Array object. The Float16Array object must use a new ArrayBuffer for its storage, and must have a zero byte offset and byte length equal to the length of its storage, in bytes. The storage ArrayBuffer must have a length of 8 × rows × pixelsPerRow bytes.

    3. If the storage ArrayBuffer could not be allocated, then rethrow the RangeError thrown by JavaScript, and return.

  3. Initialize the width attribute of imageData to pixelsPerRow.

  4. Initialize the height attribute of imageData to rows.

  5. Initialize the pixelFormat attribute of imageData to settings["pixelFormat"].

  6. If settings["colorSpace"] exists, then initialize the colorSpace attribute of imageData to settings["colorSpace"].

  7. Otherwise, if defaultColorSpace was given, then initialize the colorSpace attribute of imageData to defaultColorSpace.

  8. Otherwise, initialize the colorSpace attribute of imageData to "srgb".

ImageData objects are serializable objects. Their serialization steps, given value and serialized, are:

  1. Set serialized.[[Data]] to the sub-serialization of the value of value's data attribute.

  2. Set serialized.[[Width]] to the value of value's width attribute.

  3. Set serialized.[[Height]] to the value of value's height attribute.

  4. Set serialized.[[ColorSpace]] to the value of value's colorSpace attribute.

  5. Set serialized.[[PixelFormat]] to the value of value's pixelFormat attribute.

Their deserialization steps, given serialized, value, and targetRealm, are:

  1. Initialize value's data attribute to the sub-deserialization of serialized.[[Data]].

  2. Initialize value's width attribute to serialized.[[Width]].

  3. Initialize value's height attribute to serialized.[[Height]].

  4. Initialize value's colorSpace attribute to serialized.[[ColorSpace]].

  5. Initialize value's pixelFormat attribute to serialized.[[PixelFormat]].

The ImageDataPixelFormat enumeration is used to specify type of the data attribute of an ImageData and the arrangement and numerical representation of the color components for each pixel.

The "rgba-unorm8" value indicates that the data attribute of an ImageData must be of type Uint8ClampedArray. The color components of each pixel must be stored in four sequential elements in the order of red, green, blue, and then alpha. Each element represents the 8-bit unsigned normalized value for that component.

The "rgba-float16" value indicates that the data attribute of an ImageData must be of type Float16Array. The color components of each pixel must be stored in four sequential elements in the order of red, green, blue, and then alpha. Each element represents the value for that component.

8.10.2 The ImageBitmap interface

ImageBitmapオブジェクトは過度の待ち時間なしのキャンバスに塗装できるビットマップ画像を表す。

この過度の待ち時間は何かの正確な判断は実装者に委ねるが、一般にビットマップを活用することは、ネットワークI/O、またはローカルディスクI/Oを必要とする場合、その後待ち時間はおそらく過度である。一方それが唯一のGPUやシステムRAMからのブロッキングの読み出しを必要とする場合、待ち時間はおそらく許容できる。

promise = self.createImageBitmap(image [, options ])
promise = self.createImageBitmap(image, sx, sy, sw, sh [, options ])

img要素、SVG image要素、video要素、canvas要素、Blobオブジェクト、ImageDataオブジェクト、または別のImageBitmapオブジェクトである画像を取得し、新しいImageBitmapが作成されたときに解決されるプロミスを返す。

ImageBitmapオブジェクトを構築することが全くできない場合、たとえば、与えられたimage データが実際の画像ではないので、代わりにプロミスが却下される。

sxsysw、およびsh引数が指定される場合、ソース画像は与えられたピクセルに切り取られ、元のピクセルに欠けているピクセルは透明な黒に置き換えられる。これらの座標は、CSSピクセルではなく、ソース画像のピクセル座標空間にある。

optionsが指定される場合、ImageBitmapオブジェクトのビットマップデータはoptionsに従って変更される。For example, if the premultiplyAlpha option is set to "premultiply", the bitmap data's non-alpha color components are premultiplied by the alpha component.

ソース画像が有効な状態にない場合、"InvalidStateError" DOMExceptionを拒否する(たとえば、正常に読み込まれなかったimg要素、[[Detached]]内部スロット値がtrueのImageBitmapオブジェクト、data属性値の[[ViewedArrayBuffer]]内部スロットが切り離されているImageDataオブジェクト、データがビットマップイメージとして解釈できないBlobなど)。

スクリプトがソース画像の画像データへのアクセスを許可されていない場合、"SecurityError" DOMExceptionでプロミスを拒否する(たとえば、生成元をまたぐCORSであるvideo、別の生成元からのワーカーのスクリプトで描画されたcanvasなど)。

imageBitmap.close()

imageBitmapの基礎となるビットマップデータを解放する。

imageBitmap.width

画像の自然幅CSSピクセルで返す。

imageBitmap.height

画像の自然高さCSSピクセルで返す。

このAPIを使用すると、スプライトシートは、プレカットと調製することができる:

var sprites = {};
function loadMySprites() {
  var image = new Image();
  image.src = 'mysprites.png';
  var resolver;
  var promise = new Promise(function (arg) { resolver = arg });
  image.onload = function () {
    resolver(Promise.all([
      createImageBitmap(image,  0,  0, 40, 40).then(function (image) { sprites.person = image }),
      createImageBitmap(image, 40,  0, 40, 40).then(function (image) { sprites.grass  = image }),
      createImageBitmap(image, 80,  0, 40, 40).then(function (image) { sprites.tree   = image }),
      createImageBitmap(image,  0, 40, 40, 40).then(function (image) { sprites.hut    = image }),
      createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple  = image }),
      createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake  = image })
    ]));
  };
  return promise;
}

function runDemo() {
  var canvas = document.querySelector('canvas#demo');
  var context = canvas.getContext('2d');
  context.drawImage(sprites.tree, 30, 10);
  context.drawImage(sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

8.11 アニメーションフレーム

一部のオブジェクトにはAnimationFrameProviderインターフェイスミックスインが含まれる。

AnimationFrameProviderオブジェクトはまた、プロバイダーの内部状態を格納するターゲットオブジェクトを持つ。これは次のように定義される:

AnimationFrameProviderWindowである場合
Window関連付けられたDocument
AnimationFrameProviderDedicatedWorkerGlobalScopeである場合
DedicatedWorkerGlobalScope

ターゲットオブジェクトは、アニメーションフレームコールバックのマップ、これは初期は空でなければならない順序付きマップである、およびアニメーションフレームコールバック識別子、これは初期は0でなければならない数、を持つ。

次のいずれかが当てはまる場合、AnimationFrameProviderプロバイダーサポートされるとみなされる:


Window/requestAnimationFrame

Support in all current engines.

Firefox23+Safari7+Chrome24+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android23+Safari iOS?Chrome Android?WebView Android4.4+Samsung Internet?Opera Android?

The requestAnimationFrame(callback) method steps are:

  1. If this is not supported, then throw a "NotSupportedError" DOMException.

  2. Let target be this's target object.

  3. Increment target's animation frame callback identifier by one, and let handle be the result.

  4. Let callbacks be target's map of animation frame callbacks.

  5. Set callbacks[handle] to callback.

  6. Return handle.

Window/cancelAnimationFrame

Support in all current engines.

Firefox23+Safari7+Chrome24+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The cancelAnimationFrame(handle) method steps are:

  1. If this is not supported, then throw a "NotSupportedError" DOMException.

  2. Let callbacks be this's target object's map of animation frame callbacks.

  3. Remove callbacks[handle].

To run the animation frame callbacks for a target object target with a timestamp now:

  1. Let callbacks be target's map of animation frame callbacks.

  2. Let callbackHandles be the result of getting the keys of callbacks.

  3. For each handle in callbackHandles, if handle exists in callbacks:

    1. Let callback be callbacks[handle].

    2. Remove callbacks[handle].

    3. Invoke callback with « now » and "report".

ワーカー内部では、canvas要素から転送されたOffscreenCanvasと一緒にrequestAnimationFrame()を使用することができる。まず、文書内で、ワーカーに制御を転送する:

const offscreenCanvas = document.getElementById("c").transferControlToOffscreen();
worker.postMessage(offscreenCanvas, [offscreenCanvas]);

次に、ワーカーにおいて、次のコードで左から右に移動する矩形を描画する:

let ctx, pos = 0;
function draw(dt) {
  ctx.clearRect(0, 0, 100, 100);
  ctx.fillRect(pos, 0, 10, 10);
  pos += 10 * dt;
  requestAnimationFrame(draw);
}

self.onmessage = function(ev) {
  const transferredCanvas = ev.data;
  ctx = transferredCanvas.getContext("2d");
  draw();
};