I\'m trying to create a small 2D game in Javascript/Canvas which consists of several animated sprites. I\'d like to cut down on the number of HTTP requests, so I combined ea
Just load the image in an img tag with style attribute display set to hidden. Then crop the image on an off screen canvas, then write that off screen canvas to your main canvas as required.
Have a look at Pixastic, specifically http://www.pixastic.com/lib/docs/actions/crop.
If you don't want to use canvas or 3rd party library, you could add the image to a div (with "overflow: hidden") of the size of the cropped version, and giving the image negative left and top margins.
Each one will carry the whole image around, but will just display a portion of it, which may -- or may not -- impact performance. I believe you may have to give the div element a position:relative as well to make IE happy.
Alternatively you could assign the image as a background of the div, and specify the backgroundPosition. I seem to remember this didn't work for something I did once, not sure why. (I think it had to do with opacity)
The HTML5 Canvas API provides a method called drawImage which allows you to crop the input image.
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
For more information see the spec (that image is taken directly from the spec):
http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#images