user43353 user43353 - 2 years ago 153
Javascript Question

How to get images from a texture atlas with Javascript?

A spritesheet image object that contains sprites...

var spritesheet = new Image(); spritesheet.src ="foo.png";

I would like to be able to get a sub image from that spritesheet variable with the desired x, y, width, and height. And then assign a variable that is the sub image of the spritesheet.

How do I do that?

Answer Source

Here's one way:

  • Create an in-memory canvas to clip the subsprite pixels from the spritesheet and draw those clipped pixels on that canvas

  • Create a new subsprite image from that canvas's dataURL.

Example code (not tested--may need tweeking):

var spritesheet = new Image();

    // specify desired x,y,width,height
    // to be clipped from the spritesheet
    var x=0; 
    var y=0;
    var w=10;
    var h=10;

    // create an in-memory canvas
    var canvas=document.createElement('canvas');
    var ctx=canvas.getContext('2d');

    // size the canvas to the desired sub-sprite size

    // clip the sub-sprite from x,y,w,h on the spritesheet image
    // and draw the clipped sub-sprite on the canvas at 0,0
    ctx.drawImage(spritesheet,  x,y,w,h,  0,0,w,y);

    // convert the canvas to an image
    var subsprite=new Image();
    subsprite.onload=function(){ doCallback(subsprite); };

spritesheet.src ="foo.png";

function doCallback(img){
    // do something with the new subsprite image
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download