Copy and crop images in Javascript

China☆狼群 提交于 2019-11-27 14:06:26

问题


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.


回答1:


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




回答2:


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




回答3:


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.




回答4:


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)



来源:https://stackoverflow.com/questions/4200374/copy-and-crop-images-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!