I’ve been using the fetch API. Most examples use .json() to resolve the response body as JSON.
Alternatively, fetch offers the methods arrayBuffer() and blob() to take the response stream and return a arrayBuffer or blob, respectively. I have been trying to read up about them on MDN, but I’m not left much the wiser. What are they useful for?
A Blob just holds some raw data; outside of fetch()
, you may have come across blobs in form of a File object. An example would be to fetch()
an image that you don’t want to display directly (as in img.src = '...'
), but extract sprites to render in a canvas
:
const ctx = document
.querySelector('.game-canvas')
.getContext('2d')
window.fetch('./sprites.png')
.then(res => res.blob())
.then(blob => Promise.all([
window.createImageBitmap(blob, 0, 0, 32, 32),
window.createImageBitmap(blob, 32, 0, 32, 32)
]))
.then(([
spaceShipSprite,
enemySprite
]) => {
ctx.drawImage(spaceShipSprite, 0, 0)
ctx.drawImage(enemySprite, 256, 0)
// ... game logic here
})
.catch(reason => {
console.error('Error loading sprites:', reason)
})
Now if you want to read or manipulate some binary data directly, you can create a view from an ArrayBuffer (this can either be a typed array, or a DataView if you need an interface to handle more complex/heterogeneous data structures). An example would be if you want to process a file type that the browser doesn’t understand natively; say I invented my super-useful character encoding where ASCII codes are getting stored as 64 bit floats, I could decode such a file like
window.fetch('./some-text.ascii64')
.then(res => res.arrayBuffer())
// Here's where the decoding happens. If you wanted to
// manually decode an UTF-8 file, you would create an
// Uint8Array from the buffer instead of a Float64Array
.then(buffer => new Float64Array(buffer))
.then(bufferView => String.fromCharCode(...bufferView))
.then(console.log)
.catch(console.error)
Thanks @m3g4p0p, useful info.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.