Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 444
Cassie Meharry Avatar asked Nov 17 '10 00:11

Cassie Meharry


People also ask

How do you scale an image in JavaScript?

Image resizing in JavaScript - Using canvas element. The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. Resizing images in browser using canvas is relatively simple. drawImage function allows us to render and scale images on canvas element.


1 Answers

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)

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

like image 133
mike Avatar answered Oct 15 '22 08:10

mike