createImageBitmap() global function
Note: This feature is available in Web Workers .
The
createImageBitmap()
method creates a bitmap from a
given source, optionally cropped to contain only a portion of that source. The method
exists on the global scope in both windows and workers. It accepts a variety of
different image sources, and returns a
Promise
which resolves to an
ImageBitmap
.
Syntax
createImageBitmap(image)
createImageBitmap(image, options)
createImageBitmap(image, sx, sy, sw, sh)
createImageBitmap(image, sx, sy, sw, sh, options)
Parameters
-
image
An image source, which can be any one of the following:
HTMLImageElement
SVGImageElement
HTMLVideoElement
HTMLCanvasElement
ImageData
ImageBitmap
OffscreenCanvas
ImageBitmap
will be extracted.
The y coordinate of the reference point of the rectangle from which the
ImageBitmap
will be extracted.
The width of the rectangle from which the
ImageBitmap
will be
extracted. This value can be negative.
The height of the rectangle from which the
ImageBitmap
will be
extracted. This value can be negative.
options
Optional
An object that sets options for the image's extraction. The available options are:
imageOrientation
none
(default) or
flipY
.
premultiplyAlpha
none
,
premultiply
, or
default
(default).
colorSpaceConversion
none
or
default
(default). The value
default
indicates that implementation-specific
behavior is used.
resizeWidth
A long integer that indicates the output width.
resizeHeight
A long integer that indicates the output height.
resizeQuality
pixelated
,
low
(default),
medium
, or
high
.
Return value
A
Promise
which resolves to an
ImageBitmap
object
containing bitmap data from the given rectangle.
Examples
Creating sprites from a sprite sheet
This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. A sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately.
const canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
image = new Image();
// Wait for the sprite sheet to load
image.onload = () => {
Promise.all([
// Cut out two sprites from the sprite sheet
createImageBitmap(image, 0, 0, 32, 32),
createImageBitmap(image, 32, 0, 32, 32),
]).then((sprites) => {
// Draw each sprite onto the canvas
ctx.drawImage(sprites[0], 0, 0);
ctx.drawImage(sprites[1], 32, 32);
});