在 Javascript 中复制和裁剪图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4200374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:40:36  来源:igfitidea点击:

Copy and crop images in Javascript

javascriptcanvasclient-sidecrop

提问by Nick Meharry

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.

我正在尝试在 Javascript/Canvas 中创建一个小型 2D 游戏,其中包含多个动画精灵。我想减少 HTTP 请求的数量,因此我将动画的每一帧(32 像素 x 32 像素)合并为每个精灵的一个图像(例如,192 像素 x 128 像素)。有什么方法可以将客户端的这些图像复制并裁剪回几个较小的图像?它将极大地简化我的渲染代码,并有助于减少由于网络延迟而导致的加载时间。

采纳答案by Matt Ball

回答by mike

The HTML5 Canvas API provides a method called drawImage which allows you to crop the input image.

HTML5 Canvas API 提供了一种称为 drawImage 的方法,它允许您裁剪输入图像。

context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

alt text

替代文字

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

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#images

回答by Cris Stringfellow

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.

只需将图像加载到 img 标签中,并将样式属性显示设置为隐藏。然后在屏幕外画布上裁剪图像,然后根据需要将该屏幕外画布写入主画布。

回答by rob

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.

如果您不想使用画布或第 3 方库,您可以将图像添加到裁剪版本大小的 div(带有“溢出:隐藏”),并为图像提供负的左边距和上边距。
每个人都会携带整个图像,但只会显示其中的一部分,这可能会——也可能不会——影响性能。我相信你可能必须给 div 元素一个 position:relative 以及让 IE 开心。

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)

或者,您可以将图像指定为 div 的背景,并指定 backgroundPosition。我似乎记得这对我曾经做过的事情不起作用,不知道为什么。(我认为这与不透明度有关)