Javascript Get Image Object From Sprite

1.5k views Asked by At

I'd like to use a spritesheet to reduce the number of HTTP requests times for a tile game.

Assuming there are about 2000 different types of tiles, that's 2000 requests less for each time the game is loaded.

The sprite is 64 pixels high and contains 64 by 64 pixel tiles.

The following code retrieves the single image and starts rendering:

var tiles = new Image();
tiles.src = "tiles.png";

tiles.onload = function() {
    startRendering();
};

My question is, how could I retrieve individual Image objects from this?

1

There are 1 answers

1
Kamran Ahmed On BEST ANSWER

You will not be able to do that with pure JS. I am afraid, you will have to use bit of a CSS to achieve that.

For example lets say, instead of an img you have a

<span class="imageholder" style="padding: 64px;"></span>

Now in your javascript, you may use the following

...

tiles.backgroundImage = 'url(tiles.png)';
tiles.backgroundPosition = '0px 0px'; // apply the position to get any of the image at any position

...