Extracting Bitmaps

createImageBitmap(source, [sx, sy, sw, sh], [options]) decodes an image, canvas, video frame, Blob or ImageData into an ImageBitmap, optionally cropped, and returns a promise. Decoding happens up front, so drawing the bitmap is fast, which suits sprites and games. Options include resizeWidth, resizeHeight and imageOrientation. It is Baseline since December 2023.

Cutting frames out of a sprite sheetHTMLLive
<canvas id="sheet" width="240" height="60"></canvas>
<canvas id="view" width="320" height="60"></canvas>
<script>
  const sheet = document.querySelector('#sheet').getContext('2d');
  ['#1565c0', '#2e7d32', '#ef6c00', '#6a1b9a'].forEach((color, i) => {   // a 4-frame sheet
    sheet.fillStyle = color;
    sheet.fillRect(i * 60 + 24 - i * 6, 24 - i * 6, 12 + i * 12, 12 + i * 12);
  });
  const crops = [0, 1, 2, 3].map((i) => createImageBitmap(sheet.canvas, i * 60, 0, 60, 60,
    { resizeWidth: 40, resizeHeight: 40 }));
  const view = document.querySelector('#view').getContext('2d');
  Promise.all(crops).then((frames) => frames.reverse()
    .forEach((bitmap, i) => view.drawImage(bitmap, 10 + i * 80, 10)));
</script>
Browser output of Listing 8.13
Browser output of 13

The right canvas shows the cropped, shrunken frames in reverse. ImageBitmap is transferable, so a Web Worker can decode images and post them back without copying; bitmap.close() frees its memory.