javascripthtmlcssspritechipset

What is a high performance way of splitting up Sprite Sheets/ Chip Sets in JS?


I'm working on a 2d world editor for html/js, and trying to find the best way to split up a chip set (as seen below) into multiple little squares (chips).

Currently, I'm using a method similar to the default css sprite sheets method, of using background position to move the background of many little <div> elements until each displays one square/chip of the chip set.

It is working fine, with no big performance issues, but it seems like an overall clunky way to do it.

Other ways I've thought of doing it would be to slice the chip set into many temporary images and make an <image> element for each, or using <canvas> instead of <div>'s or <image>'s

Anyways, I'm looking for advice on the subject:

What is a high performance way of splitting up Sprite Sheets/ Chip Sets in JS?

example chip set

example of a chip set


Solution

  • The way you're doing it right now should be pretty fast. You could essentially reimplement that on the canvas level by storing just the one image then using drawImage to only draw sections from it. To the best of my knowledge, this is the most common way and is very fast. At least that was my experience when I wrote a game engine using canvas.

    Using the canvas is most likely faster and more memory efficient since you don't have the additional DOM overhead but you'd have to measure it for your specific use case and verify that.

    Creating a bunch of individual images, as you suggested, would be very slow since it'd require copying portions of the image and creating an additional DOM element for each image.

    In short: using the canvas will always be faster (for a comparable implementation) since you're almost directly interfacing with the GPU. Drawing from one image rather than copying it into multiple sub images will always be faster since you won't have duplicate memory sitting around and as long as you're drawing from the same sheet, the GPU doesn't have to switch out the texture.