Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I would like to reduce the size of the spritesheet I am loading by only loading the specific sprites I need. Is there a way to crop and splice images at runtime using javascript? Creating separate spritesheets for each level is not ideal, as that would mean lots of repeated sprites.

edit for clarification: Say I want to replace the 5 sprites in the top right corner of my spritesheet based on user input. Is there a way to remove the sprites that are there and replace them with some from a different file?

share|improve this question
3  
Your question title and body seem to ask a different question. –  sm4 Jun 14 '13 at 14:55
    
I'd like to pack only the images I want into a spritesheet at runtime. Say I want to replace the 5 sprites in the top right corner of my spritesheet based on user input. Is there a way to remove the sprites that are there and replace them with some from a different file? –  nate Jun 14 '13 at 14:57
add comment

3 Answers 3

Sure. You can create an offscreen canvas:

var modifiedSpriteSheet = document.createElement('canvas');
//Your dimensions here
modifiedSpriteSheet.width = 400;
modifiedSpriteSheet.height = 400;
var modifiedContext = modifiedSpriteSheet.getContext('2d');

...and draw exactly which graphics you want to use to the context. Of course, the images you are pulling from will have to finish loading first.

if(userInput === 34) { //Whatever your logic is...
    modifiedContext.drawImage(img1, 0, 0, 32, 32, 64, 0, 32, 32);
} else {
    modifiedContext.drawImage(img1, 32, 0, 32, 32, 64, 0, 32, 32); //Different!
}

When finished with logic, you can then draw the off-screen canvas you created and use it as if it were an image.

drawingContext.drawImage(modifiedSpriteSheet, 64, 0, 32, 32, 0, 0, 32, 32);

That should be all!

share|improve this answer
add comment

You are overthinking it, if you want to do context dependent loading just make one sprite sheet for the common graphics and one for each specific context. There is no need to combine them.

share|improve this answer
    
I actually agree what he has to say if you want to do this practically. –  Marc Marta Jun 17 '13 at 13:32
add comment

Yes there is, you can make a composite image for your sprite sheet using the drawImage() canvas method out of the two original images.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.