Crop image on the client side with JCrop and HTML5 canvas element

Suppose you are working on a nice web application where the user can upload images to, for example, a shop catalogue (mmm… that makes me think on something :p ) but wait… you don’t the catalogue uses the whole image you upload instead a piece of it. So, we need to crop the image.

Click for demo

I won’t go in depth on how to create the whole process, in summary:

  1. User choose an images and app upload to server.
  2. Wep app shows the images to user and allows him/her to crop the desired piece of image.
  3. Crop parameters (x, y, widht, height) are sent to server which responsible to really crop the image.

Here we talk about the step 2: the web page that allows to crop (or choose some image area) and send the parameters to the serve to make the real crop (for example using GD or ImageMagick).

The real magic comes from JCrop, a jQuery plugin to select areas within an image. As I note in the demo, in the JCrop project page there is a demo that makes a preview of the selection using two <img> elements.

Here the we are going to make something very similar but using the HTML5 canvas element (to practice a bit :p).

The first step is to add one img element pointing to the image and one canvas element which will act as the previous:

Now the code that preview the selected cropped image every time the user updates the selected area:

As you can see the main parameters are the coordinate fields (variable ‘c’). One way to send it to server is to store in four hidden input filed in a form, and send them on submit.

Looking again to the post I think there are too much words to simply show an easy HTML5 canvas example :)

3 Responses

  1. mbasia April 2, 2012 / 12:18

    Hi. Everything ok, but if you click contex menu to show picture there is expanded one insteed squared. How to diplay it the same as is in preview?
    What about in case if the image is bigger and I want to scale it? Then the coordinates do not overlap. Is there any solution for that?

  2. Bernie October 8, 2012 / 13:35

    Excelent resource! Thank you very much.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">