神经性皮炎用什么药| 晕车吃什么能缓解| 肾素低说明什么| 眉眼是什么意思| 维生素c弱阳性是什么意思| 难以启齿什么意思| 经常口腔溃疡挂什么科| 一年一片避孕药叫什么| 三月十五日是什么星座| 启五行属什么| 益母草什么时候喝最好| 1r是什么意思| 空气炸锅能做什么| 蜂蜜加柠檬有什么功效和作用| 总是流鼻血是什么原因| 鳄鱼的尾巴有什么作用| 高血压吃什么药效果好| 乳腺结节是什么原因引起的| 糖尿病可以喝什么饮料| 总出虚汗什么原因怎么解决| sec是什么意思| 经期量少吃什么来排血| 用激素药有什么副作用| 腰痛宁为什么晚上吃| 尿白细胞阳性什么意思| 梨和什么一起榨汁好喝| 什么叫痉挛| 咳嗽吃什么药好| 骨质疏松吃什么钙片| 玉兰片和竹笋有什么区别| 一龙一什么填十二生肖| 软组织挫伤用什么药| 胎心停了会有什么症状| 缪读什么| 怀孕什么时候打胎最合适| 胸闷想吐是什么原因| 捡和拣有什么区别| 什么是违反禁令标志指示| 仪字五行属什么| 困水是什么意思| 姨妈安全期是什么时候| 什么时候阅兵| pvd是什么意思| 白带是什么颜色的| 吃什么安神有助于睡眠| 天龙八部是指佛教中的什么| 然五行属什么| covu药片是什么药| 脑炎是什么症状| 治疗荨麻疹用什么药最好| 化疗期间吃什么水果好| 不成敬意什么意思| 慢阻肺吃什么药最有效最好| 泌乳素过高女性会出现什么症状| 必要条件是什么意思| 蜂蜜加柠檬有什么功效和作用| 肠胃挂什么科| 三无是什么意思| mini是什么车| 冠心病是什么| 癸水是什么| 日本桑是什么意思| 什么是有机磷农药| 甲状腺结节忌口什么| 脾肾阳虚是什么意思| 备孕去医院挂什么科| 大姨妈期间可以吃什么水果| 长乘宽乘高算的是什么| 临床表现是什么意思| 鸡骨草有什么功效| 冰箱买什么牌子好| 蒲公英泡水喝有什么功效| 半夜口干舌燥是什么原因| 喉咙有异物感看什么科| 水瓶男和什么星座最配| 逝去是什么意思| 6.25什么星座| 新生儿呛奶是什么原因引起的| 克星是什么意思| 舒五行属什么| 犹太是什么意思| 腰疼吃什么药| 大腿后侧肌肉叫什么| 绿本是什么| 菱角什么时候成熟| 胃溃疡能吃什么水果| 什么照片看不出照的是谁| 血氧低吃什么药效果好| sparkling是什么意思| 不饱和脂肪酸是什么意思| 虚是什么意思| 锁钥是什么意思| 什么鸡蛋营养价值最高| 女生经常手淫有什么危害| 尾巴长长的是什么鸟| 梦到和男朋友分手是什么征兆| 排卵期有什么明显症状| 滴虫性阴道炎用什么药效果最好| 甲状腺去医院挂什么科| 6月16什么星座| 防微杜渐是什么意思| 巴利属于什么档次的| 牛膝有什么功效| 后背不舒服是什么原因| 晚餐吃什么菜谱大全| 死是什么感觉| 日本人什么时候投降的| 重阳节为什么要插茱萸| 慧眼识珠是什么意思| 茉字五行属什么| 磨皮是什么意思| 什么是气胸有什么症状| 金碧辉煌是什么生肖| 出大汗是什么原因| 急性牙髓炎吃什么药| 头不舒服是什么原因| 轻度肠化是什么意思| 解痉镇痛酊有什么功效| 手淫过多会导致什么| 黄体什么意思| 但爱鲈鱼美的但是什么意思| 减张缝合是什么意思| 孕妇梦到老公出轨什么意思| 血尿挂什么科| 王禹读什么| 小孩子肚子疼吃什么药| 总出虚汗什么原因怎么解决| 升天是什么意思| 房性期前收缩是什么意思| 为什么一分钟就出来了| 老有眼屎是什么原因| 料酒是什么酒| 为什么会长湿疹| 肝郁血瘀吃什么中成药| 72年鼠是什么命| 担心是什么意思| 木灵念什么| 辗转反侧什么意思| 决明子泡水喝有什么功效| c3是什么| 头疼恶心想吐是什么原因| 脸过敏用什么药膏效果最好| 嬴稷和嬴政什么关系| 家里养泥鳅喂什么东西| 梦见火烧房子是什么预兆| 水苏糖是什么东西| 龟头有红点用什么药| 辟邪剑谱和葵花宝典有什么关系| 次数是什么| 频繁是什么意思| 气泡水是什么水| 什么是交感神经紊乱| 71年出生属什么生肖| RH阳性什么意思| 齐活儿是什么意思| 捉奸什么意思| 吃什么通大便最快| 肛门坠胀吃什么药最好| 荨麻疹可以吃什么| 阴虱长什么样| 红曲是什么| 椒盐是什么调料| 什么样的乌云| 什么东西越洗越脏答案| 黑道是什么意思| 336是什么意思| 桃李满天下的桃李是什么意思| 吃什么美容养颜抗衰老| 女人眼睛干涩吃什么药| 3月9号是什么星座| 喝红枣水有什么好处和坏处| 爱的意义是什么| 吃黑豆有什么好处和坏处| 什么是肌无力| 唐顿庄园讲的是什么| 鹿晗有什么歌| 槟榔为什么那么贵| 所向披靡什么意思| 手腕关节疼痛什么原因引起的| 吃蝎子有什么好处| 孕妇白蛋白偏低是什么意思| 画画用什么铅笔| 心电图窦性心律不齐是什么意思| 一个三点水一个及念什么| rf是什么的缩写| 头皮屑多用什么洗发水效果好| 固体饮料是什么意思| 敢爱敢恨是什么意思| 省委组织部长是什么级别| 今天什么时候出梅| 统战部是干什么的| 月经每个月都推迟是什么原因| 黑裙配什么颜色的上衣| id是什么意思的缩写| 喝枸杞水有什么好处| 十年粤语版叫什么名字| 大象像什么| BS是什么意思啊| 什么是基因| 起死回生是什么生肖| 吃什么降血压| 胎盘成熟度0级什么意思| 观落阴是什么意思| 豆奶不能和什么一起吃| 苋菜什么人不能吃| 又吐又拉是什么原因| 神经痛吃什么药效果好| 沙参长什么样子图片| 六月生日是什么星座| 高处不胜寒是什么意思| 空调病是什么| 补钾用什么药| 7月14号是什么节日| 宫颈出血是什么症状| 腿毛旺盛是什么原因| 舒张压偏高是什么原因| 雪莲果什么时候成熟| 黑色碳素笔是什么笔| 甲状腺有什么症状| 生气对身体有什么危害| 壁虎的尾巴有什么用| 大便稀溏是什么意思| 梦见老公穿新衣服是什么意思| 尿道灼热感吃什么药| 幽门螺杆菌什么症状| 羊水是什么颜色的| 柳树的叶子像什么| 蝙蝠飞进家里预示什么| 秦始皇叫什么名字| 做书桌用什么板材好| 骨化是什么意思| 喝酒对胃有什么伤害| 为什么不| 一个日一个斤念什么| 痤疮是什么意思| 头孢和什么药不能一起吃| 什么药治便秘最好最快| 淼字五行属什么| 白带黄是什么原因| 手腕痛挂什么科| 女仆是什么意思| 子衿什么意思| 冯庸大学现在叫什么| 正骨有什么好处和坏处| 柠檬茶喝了有什么好处| 人老了为什么会瘦| 1942年属什么生肖属相| 桃李满天下是什么生肖| 来姨妈吃什么好| 乌龟一般吃什么| 无水焗是什么意思| 什么行业最赚钱| 灵芝孢子粉治什么病| 做胃镜有什么好处| 胆结石吃什么比较好| 中度贫血吃什么补血最快| 中华田园犬为什么禁养| 6.5是什么星座| 甲醛有什么危害| 着重号是什么符号| 维生素b5药店叫什么| 什么是热病| 夏天中暑吃什么药| 什么叫脂肪肝| 百度
    1. 8.10 Images
      1. 8.10.1 The ImageData interface
      2. 8.10.2 The ImageBitmap interface
    2. 8.11 Animation frames

8.10 Images

8.10.1 The ImageData interface

ImageData

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

typedef (Uint8ClampedArray or Float16Array) ImageDataArray;

enum ImageDataPixelFormat { "rgba-unorm8", "rgba-float16" };

dictionary ImageDataSettings {
  PredefinedColorSpace colorSpace;
  ImageDataPixelFormat pixelFormat = "rgba-unorm8";
};

[Exposed=(Window,Worker),
 Serializable]
interface ImageData {
  constructor(unsigned long sw, unsigned long sh, optional ImageDataSettings settings = {});
  constructor(ImageDataArray data, unsigned long sw, optional unsigned long sh, optional ImageDataSettings settings = {});

  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  readonly attribute ImageDataArray data;
  readonly attribute ImageDataPixelFormat pixelFormat;
  readonly attribute PredefinedColorSpace colorSpace;
};

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

ImageData/ImageData

Support in all current engines.

Firefox29+Safari8+Chrome36+
Opera?Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

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

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
imageData.height

ImageData/height

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

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

imageData.data

ImageData/data

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

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

imageData.colorSpace

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:

ImageData/colorSpace

FirefoxNoSafari15.2+Chrome92+
Opera?Edge92+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
  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

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=(Window,Worker), Serializable, Transferable]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  undefined close();
};

typedef (CanvasImageSource or
         Blob or
         ImageData) ImageBitmapSource;

enum ImageOrientation { "from-image", "flipY" };
enum PremultiplyAlpha { "none", "premultiply", "default" };
enum ColorSpaceConversion { "none", "default" };
enum ResizeQuality { "pixelated", "low", "medium", "high" };

dictionary ImageBitmapOptions {
  ImageOrientation imageOrientation = "from-image";
  PremultiplyAlpha premultiplyAlpha = "default";
  ColorSpaceConversion colorSpaceConversion = "default";
  [EnforceRange] unsigned long resizeWidth;
  [EnforceRange] unsigned long resizeHeight;
  ResizeQuality resizeQuality = "low";
};

An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

promise = self.createImageBitmap(image [, options ])

createImageBitmap

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
promise = self.createImageBitmap(image, sx, sy, sw, sh [, options ])

Takes image, which can be an img element, an SVG image element, a video element, a canvas element, a Blob object, an ImageData object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image's pixel coordinate space, not in CSS pixels.

If options is provided, the ImageBitmap object's bitmap data is modified according to 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.

Rejects the promise with an "InvalidStateError" DOMException if the source image is not in a valid state (e.g., an img element that hasn't loaded successfully, an ImageBitmap object whose [[Detached]] internal slot value is true, an ImageData object whose data attribute value's [[ViewedArrayBuffer]] internal slot is detached, or a Blob whose data cannot be interpreted as a bitmap image).

Rejects the promise with a "SecurityError" DOMException if the script is not allowed to access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).

imageBitmap.close()

ImageBitmap/close

Support in all current engines.

Firefox46+Safari15+Chrome52+
Opera37+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android37+

Releases imageBitmap's underlying bitmap data.

imageBitmap.width

ImageBitmap/width

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the natural width of the image, in CSS pixels.

imageBitmap.height

ImageBitmap/height

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the natural height of the image, in CSS pixels.

An ImageBitmap object whose [[Detached]] internal slot value is false always has associated bitmap data, with a width and a height. However, it is possible for this data to be corrupted. If an ImageBitmap object's media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by content from a different origin. The flag is initially set to true and may be changed to false by the steps of createImageBitmap().


ImageBitmap objects are serializable objects and transferable objects.

Their serialization steps, given value and serialized, are:

  1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.

  2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.

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

  1. Set value's bitmap data to serialized.[[BitmapData]].

Their transfer steps, given value and dataHolder, are:

  1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.

  2. Set dataHolder.[[BitmapData]] to value's bitmap data.

  3. Unset value's bitmap data.

Their transfer-receiving steps, given dataHolder and value, are:

  1. Set value's bitmap data to dataHolder.[[BitmapData]].


The createImageBitmap method uses the bitmap task source to settle its returned Promise.

The createImageBitmap(image, options) and createImageBitmap(image, sx, sy, sw, sh, options) methods, when invoked, must run these steps:

  1. If either sw or sh is given and is 0, then return a promise rejected with a RangeError.

  2. If either options's resizeWidth or options's resizeHeight is present and is 0, then return a promise rejected with an "InvalidStateError" DOMException.

  3. Check the usability of the image argument. If this throws an exception or returns bad, then return a promise rejected with an "InvalidStateError" DOMException.

  4. Let promise be a new promise.

  5. Let imageBitmap be a new ImageBitmap object.

  6. Switch on image:

    img
    SVG image
    1. If image's media data has no natural dimensions (e.g., it's a vector graphic with no specified content size) and either options's resizeWidth or options's resizeHeight is not present, then return a promise rejected with an "InvalidStateError" DOMException.

    2. If image's media data has no natural dimensions (e.g., it's a vector graphic with no specified content size), it should be rendered to a bitmap of the size specified by the resizeWidth and the resizeHeight options.

    3. Set imageBitmap's bitmap data to a copy of image's media data, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from 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.

    4. If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.

    5. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

    video
    1. If image's networkState attribute is NETWORK_EMPTY, then return a promise rejected with an "InvalidStateError" DOMException.

    2. Set imageBitmap's bitmap data to a copy of the frame at the current playback position, at the media resource's natural width and natural height (i.e., after any aspect-ratio correction has been applied), cropped to the source rectangle with formatting.

    3. If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.

    4. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

    canvas
    1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.

    2. Set the origin-clean flag of the imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.

    3. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

    Blob

    Run these steps in parallel:

    1. Let imageData be the result of reading image's data. If an error occurs during reading of the object, then queue a global task, using the bitmap task source, to reject promise with an "InvalidStateError" DOMException and abort these steps.

    2. Apply the image sniffing rules to determine the file format of imageData, with MIME type of image (as given by image's type attribute) giving the official type.

    3. If imageData is not in a supported image file format (e.g., it's not an image at all), or if imageData is corrupted in some fatal way such that the image dimensions cannot be obtained (e.g., a vector graphic with no natural size), then queue a global task, using the bitmap task source, to reject promise with an "InvalidStateError" DOMException and abort these steps.

    4. Set imageBitmap's bitmap data to imageData, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from 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.

    5. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

    ImageData
    1. Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot.

    2. If IsDetachedBuffer(buffer) is true, then return a promise rejected with an "InvalidStateError" DOMException.

    3. Set imageBitmap's bitmap data to image's image data, cropped to the source rectangle with formatting.

    4. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

    ImageBitmap
    1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.

    2. Set the origin-clean flag of imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.

    3. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

    VideoFrame
    1. Set imageBitmap's bitmap data to a copy of image's visible pixel data, cropped to the source rectangle with formatting.

    2. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.

  7. Return promise.

When the steps above require that the user agent crop bitmap data to the source rectangle with formatting, the user agent must run the following steps:

  1. Let input be the bitmap data being transformed.

  2. If sx, sy, sw and sh are specified, let sourceRectangle be a rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh). Otherwise, let sourceRectangle be a rectangle whose corners are the four points (0, 0), (width of input, 0), (width of input, height of input), (0, height of input).

    If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point.

  3. Let outputWidth be determined as follows:

    If the resizeWidth member of options is specified
    the value of the resizeWidth member of options
    If the resizeWidth member of options is not specified, but the resizeHeight member is specified
    the width of sourceRectangle, times the value of the resizeHeight member of options, divided by the height of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the width of sourceRectangle
  4. Let outputHeight be determined as follows:

    If the resizeHeight member of options is specified
    the value of the resizeHeight member of options
    If the resizeHeight member of options is not specified, but the resizeWidth member is specified
    the height of sourceRectangle, times the value of the resizeWidth member of options, divided by the width of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the height of sourceRectangle
  5. Place input on an infinite transparent black grid plane, positioned so that its top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane's grid.

  6. Let output be the rectangle on the plane denoted by sourceRectangle.

  7. Scale output to the size specified by outputWidth and outputHeight. The user agent should use the value of the resizeQuality option to guide the choice of scaling algorithm.

  8. If the value of the imageOrientation member of options is "flipY", output must be flipped vertically, disregarding any image orientation metadata of the source (such as EXIF metadata), if any. [EXIF]

    If the value is "from-image", no extra step is needed.

    There used to be a "none" enum value. It was renamed to "from-image". In the future, "none" will be added back with a different meaning.

  9. If image is an img element or a Blob object, let val be the value of the colorSpaceConversion member of options, and then run these substeps:

    1. If val is "default", the color space conversion behavior is implementation-specific, and should be chosen according to the default color space that the implementation uses for drawing images onto the canvas.

    2. If val is "none", output must be decoded without performing any color space conversions. This means that the image decoding algorithm must ignore color profile metadata embedded in the source data as well as the display device color profile.

  10. Let val be the value of premultiplyAlpha member of options, and then run these substeps:

    1. If val is "default", the alpha premultiplication behavior is implementation-specific, and should be chosen according to implementation deems optimal for drawing images onto the canvas.

    2. If val is "premultiply", the output that is not premultiplied by alpha must have its color components multiplied by alpha and that is premultiplied by alpha must be left untouched.

    3. If val is "none", the output that is not premultiplied by alpha must be left untouched and that is premultiplied by alpha must have its color components divided by alpha.

  11. Return output.

The close() method steps are:

  1. Set this's [[Detached]] internal slot value to true.

  2. Unset this's bitmap data.

The width getter steps are:

  1. If this's [[Detached]] internal slot's value is true, then return 0.

  2. Return this's width, in CSS pixels.

The height getter steps are:

  1. If this's [[Detached]] internal slot's value is true, then return 0.

  2. Return this's height, in CSS pixels.

The ResizeQuality enumeration is used to express a preference for the interpolation quality to use when scaling images.

The "pixelated" value indicates a preference for scaling the image to preserve the pixelation of the original as much as possible, with minor smoothing as necessary to avoid distorting the image when the target size is not a clean multiple of the original.

To implement "pixelated", for each axis independently, first determine the integer multiple of its natural size that puts it closest to the target size and is greater than zero. Scale it to this integer-multiple-size using nearest neighbor, then scale it the rest of the way to the target size using bilinear interpolation.

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-scaling algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used, except for "pixelated" as described above.

Using this API, a sprite sheet can be precut and prepared:

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

Some objects include the AnimationFrameProvider interface mixin.

callback FrameRequestCallback = undefined (DOMHighResTimeStamp time);

interface mixin AnimationFrameProvider {
  unsigned long requestAnimationFrame(FrameRequestCallback callback);
  undefined cancelAnimationFrame(unsigned long handle);
};
Window includes AnimationFrameProvider;
DedicatedWorkerGlobalScope includes AnimationFrameProvider;

Each AnimationFrameProvider object also has a target object that stores the provider's internal state. It is defined as follows:

If the AnimationFrameProvider is a Window
The Window's associated Document
If the AnimationFrameProvider is a DedicatedWorkerGlobalScope
The DedicatedWorkerGlobalScope

Each target object has a map of animation frame callbacks, which is an ordered map that must be initially empty, and an animation frame callback identifier, which is a number that must initially be zero.

An AnimationFrameProvider provider is considered supported if any of the following are true:


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

Inside workers, requestAnimationFrame() can be used together with an OffscreenCanvas transferred from a canvas element. First, in the document, transfer control to the worker:

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

Then, in the worker, the following code will draw a rectangle moving from left to right:

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();
};
百度