In this article I described in detail how to optimize the loading of a large number of images into Mapbox using a sprite file.
In short, my algorithm of actions was as follows:
- load the sprite and its metadata (a JSON file with information about where each image is located in the file), which we previously generated and stored on a server as static resources
- create an OffscreenCanvas and add the loaded sprite (image) to it
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d', { willReadFrequently: true });
ctx.drawImage(image, 0, 0);
- for each required image, get it from the canvas as an image and add it to the mapbox
const imageData = ctx.getImageData(x, y, width, height);
map.addImage(imageId, imageData)