在 Javascript 中复制和裁剪图像
我正在尝试用 Javascript/Canvas 创建一个小型 2D 游戏,它由几个动画精灵组成。我想减少 HTTP 请求的数量,因此我将每一帧动画(32 像素 x 32 像素)合并为每个精灵一个图像(例如,192 像素 x 128 像素)。有什么方法可以将客户端的这些图像复制并裁剪成几个较小的图像吗?它将极大地简化我的渲染代码,并有助于减少由于网络延迟而导致的加载时间。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HTML5 Canvas API 提供了一个名为drawImage 的方法,它允许您裁剪输入图像。
有关详细信息,请参阅规范(该图像直接取自规范):
http://www.whatwg.org/specs/web- apps/current-work/multipage/the-canvas-element.html#images
The HTML5 Canvas API provides a method called drawImage which allows you to crop the input image.
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
看看Pixastic,特别是http://www.pixastic.com/lib/docs/actions/crop。
Have a look at Pixastic, specifically http://www.pixastic.com/lib/docs/actions/crop.
只需将图像加载到 img 标签中,并将样式属性显示设置为隐藏即可。然后在离屏画布上裁剪图像,然后根据需要将该离屏画布写入主画布。
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.
如果您不想使用画布或第 3 方库,您可以将图像添加到裁剪版本大小的 div(带有“overflow:hidden”),并为图像提供负左和上边距。
每个图像都会携带整个图像,但只会显示其中的一部分,这可能会(也可能不会)影响性能。我相信你可能还必须给 div 元素一个position:relative 才能让 IE 满意。
或者,您可以将图像指定为 div 的背景,并指定backgroundPosition。我似乎记得这对我曾经做过的事情不起作用,不知道为什么。 (我认为这与不透明度有关)
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)