利用 JCrop 和 HTML5 canvas元素在瀏覽器端實現圖片裁剪
圖片裁剪經常用在上傳頭像裁剪的功能上,如果要在Web應用中實現這個功能有些困難。本文將介紹如何利用Jcrop這個jQuery插件與HTML5技術實現在Web客戶端就能裁剪圖片不需要與服務端交互。
Jcrop是一個jQuery插件,它能為你的WEB應用程序快速簡單地提供圖片裁剪的功能。
特點:
- 對所有圖片均unobtrusively(無侵入的,保持DOM簡潔)
- 支持寬高比例鎖定
- 支持 minSize / maxSize設置
- 支持改變選區或移 動選區時的回調(Callback)
- 支持用鍵盤微調選 區
- 通過API創建互 動,比如動畫效果
- 支持CSS樣式
</ul>
以下英文原文自己看去吧,不會太難。 - User choose an images and app upload to server.
- Wep app shows the images to user and allows him/her to crop the desired piece of image.
- Crop parameters (x, y, widht, height) are sent to server which responsible to really crop the image. </ol>

I won’t go in depth on how to create the whole process, in summary:
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:
<img src="./sago.jpg" id="target" alt="Flowers" /> <canvas id="preview" style="width:150px;height:150px;overflow:hidden;"></canvas>Now the code that preview the selected cropped image every time the user updates the selected area:
$('#target').Jcrop({ onChange : updatePreview, onSelect : updatePreview, aspectRatio : 1 });function updatePreview(c) { if(parseInt(c.w) > 0) { // Show image preview var imageObj = $("#target")[0]; var canvas = $("#preview")[0]; var context = canvas.getContext("2d"); context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height); } };</pre>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 many words to simply show an easy HTML5 canvas example
Source: http://acuriousanimal.com/blog/2011/09/26/crop-image-on-the-client-side-with-jcrop-and-html5-canvas-element/