开发者

Copy and crop images in Javascript

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 each frame of animation (32px by 32px) into one image per sprite (say, 192px by 128px). Is there any way I can copy and crop these images clientside back into several smaller images? It would vastly simplify my rendering code and help reduce loading time due to network latency.


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)

Copy and crop images in Javascript

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


Have a look at Pixastic, specifically http://www.pixastic.com/lib/docs/actions/crop.


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜