2

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.

2
  • Are you asking about how to preload the spritesheet or how to apply it to elements? Commented Feb 17, 2013 at 15:00
  • Hmm. Both, I think. I want to use it within the canvas. Commented Feb 17, 2013 at 15:01

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.