Learn to Code via Tutorials on Repl.it!

← Back to all posts
Loading Images in Web Workers
tussiez (874)

Images in Web Workers

Loading images in Web Workers with Image() doesn't work (needs access to DOM), so you'll need to use fetch and createImageBitmap to use images.


let response = fetch(imgURL).then(response => response.blob())

The code above fetches the image from imgURL, and then converts the response to a blob, which is used for files.

Adding on to the same line:

.then(blob => {

createImageBitmap creates a usable image from the blob response.
x/yStart is the starting position to create the image from.
x/yEnd is the position that the image should end at.
If you want to get the entire image, use 0,0,imgWidth,imgHeight.

createImageBitmap is also an async function, so you'll need to use then here too, adding onto the end of the function:

.then(img => {
//img is the image! You can use this however you wish.

TL;DR code

Here's all of the code put together:

let response = fetch(imgURL).then(response => response.blob()).then(blob => {
createImageBitmap(blob,0,0,width,height).then(img => {
//img is the image

Example: Reverse texture atlas generator in SortaCraft

Hope this helps!