In this tutorial we’re going to learn how to resize and crop an image using the HTML5
<canvas>
element, and while we’re at it, let’s create some fancy controls for resizing, commonly seen in photo editing applications.In a real world example a website or app might use a technique like this to resize and frame a profile picture before uploading. Whilst we could do this on the server, it would require the transfer of a potentially large file, which is slow. Instead we can resize the image on the client side before uploading it, which is fast.
We do this by creating an HTML5
<canvas>
element
and drawing the image to the canvas at a particular size, then
extracting the new image data from the canvas as a data URI. Most
browsers have good support for these methods, so you can probably use
this technique right now, however just be aware of some limitations
unrelated to browser support such as quality and performance.Resizing very large images can cause the browser to slow down or in some cases, even crash. It makes sense to set reasonable limits on the file size just as you would when uploading a file. If quality is important you may find the resized image looks undesirable due to how the browser resampled it. There are some techniques to improve the quality of images downscaled with canvas, but they are not covered in this tutorial.
Take a look at the final result in this demo or download the ZIP file.
0 comments:
Post a Comment