Search code examples
javascriptcssbackground-imageimage-preloader

How to use preloaded CSS spritesheet in javascript?


I'm making a game using HTML5 canvas. I have a large spritesheet which contains every sprite I'll need within the game. I have read a bit on what might be the best preloading asset technique, and I haven't found anything concrete.

So, I decided I'll just choose one technique: CSS spritesheets. I've used http://www.spritecow.com/ where I've loaded the spritesheet.gif file and generated the CSS code. The thing is that I couldn't find any tutorials on how to actually USE the individual sprites within javascript and the canvas element!

Can someone give me a hand? If you know any other preloading technique or library that is better (can preload images and sounds, if possible).

EDIT: A solution with jQuery is fine too.


Solution

  • Preloading:

    A sprite sheet is just an image, so preload like you would any other image. That said, a "jQuery way" would be: var $mySprite = $("<img>").attr("src", "myURL");

    (Source: Preload a spritesheet using Jquery)

    Applying to elements:

    No need to use javascript as this can be done with simple css.

    1 - Add a sprite class to every element that uses the spritesheet:

    html: <div class="sprite">

    css: .sprite { background-image:url("your spritesheet url here") }

    2 - Add ids to your elements, and then matching css background-position rules, according to the location of the specific element's image on the spritesheet. e.g.

    html: <div class="sprite" id="fire"></div>

    css:

    #fire {
      background-position: -100px -50px;
      height: 20px;
      width:  40px;
    }