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
.
createImageBitmap(image)
createImageBitmap(image, options)
createImageBitmap(image, sx, sy, sw, sh)
createImageBitmap(image, sx, sy, sw, sh, options)
A Promise
which resolves to an ImageBitmap
object containing bitmap data from the given rectangle.
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();
image.onload = () => {
Promise.all([
createImageBitmap(image, 0, 0, 32, 32),
createImageBitmap(image, 32, 0, 32, 32),
]).then((sprites) => {
ctx.drawImage(sprites[0], 0, 0);
ctx.drawImage(sprites[1], 32, 32);
});
};
image.src = "sprites.png";