1
\$\begingroup\$

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?

\$\endgroup\$
2
  • 3
    \$\begingroup\$ Your question title and body seem to ask a different question. \$\endgroup\$ Commented Jun 14, 2013 at 14:55
  • \$\begingroup\$ 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? \$\endgroup\$
    – nate
    Commented Jun 14, 2013 at 14:57

3 Answers 3

3
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ I actually agree what he has to say if you want to do this practically. \$\endgroup\$
    – Marc Marta
    Commented Jun 17, 2013 at 13:32
0
\$\begingroup\$

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

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .