2008年8月22日星期五

rails crop image use paperclip and jquery

More and more sites begin to allow user to crop their avatar.
After some time google, I haven't found a easy way to implement this in rails use jquery and paperclip.
So I think maybe this article is helpful.

First I install a jquery plugin imaareaselect , it works well.

I add it in the view,
 
<% content_for :head do %>
<%= javascript_include_tag 'jquery-areaselect' %>
<% javascript_tag do -%>
$(window).load(function () { $('#duck').imgAreaSelect({ x1: 120, y1: 90, x2: 280, y2: 210, onSelectEnd: set_crop });
});
function set_crop(img, selection){
$('#crop_left').val(selection.x1)
$('#crop_top').val(selection.y1)
$('#crop_width').val(selection.width)
$('#crop_height').val(selection.height)
}
<% end -%>
<% end %>


and these lines in a form

 

<%= hidden_field_tag "crop_left", "0" %>


<%= hidden_field_tag "crop_top", "0" %>


<%= hidden_field_tag "crop_width", "1" %>


<%= hidden_field_tag "crop_height", "1" %>



<%= image_tag current_user.photo.url(:large), :id => "duck" %>


then I write some codes in a moudle, this is the file:


I will extract this as a paperclip extention later. In fact, you can this with prototype too.

没有评论: