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?

• 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

Sure. You can create an offscreen canvas:

var modifiedSpriteSheet = document.createElement('canvas');
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!

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.

• I actually agree what he has to say if you want to do this practically. – Marc Marta Jun 17 '13 at 13:32

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