I am trying to use Carrierwave with Jcrop in the exact same way as Ryan Bates uses it in RailsCasts Episode 182 (revised) but I just can't get Jcrop to work and I can't figure out why.
When I get to crop.html.erb
, it shows the original picture and the preview as expected but I can't select anything on the original picture and the preview is not responding.
I have played around a little bit and when I add the ()
behind .Jcrop
I can at least select something on the original picture but the preview is still not responding and the selected area is also not keeping the aspectRatio of 1. So I guess for some reason the code after .Jcrop
is not executed. I am not a CoffeeScript expert so I need some help with figuring this out.
Here is my code. Thanks a lot!
user.js.coffee
:
jQuery ->
new AvatarCropper()
class AvatarCropper
constructor: ->
$('#cropbox').Jcrop() ->
aspectRatio: 1
setSelect: [0, 0, 500, 500]
onSelect: @update
onChange: @update
update: (coords) =>
$('#user_crop_x').val(coords.x)
$('#user_crop_y').val(coords.y)
$('#user_crop_w').val(coords.w)
$('#user_crop_h').val(coords.h)
@updatePreview(coords)
updatePreview: (coords) =>
$('#preview').css
width: Math.round(100/coords.w * $('#cropbox').width()) + 'px'
height: Math.round(100/coords.h * $('#cropbox').height()) + 'px'
marginLeft: '-' + Math.round(100/coords.w * coords.x) + 'px'
marginTop: '-' + Math.round(100/coords.h * coords.y) + 'px'
users_controller.rb
:
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
if params[:user][:avatar].present?
render :crop
else
redirect_to @user, notice: "Successfully updated user."
end
else
render :new
end
end
def crop
@user = User.find(params[:id])
render view: "crop"
end
users/crop.html.erb
:
<h1>Crop Avatar</h1>
<%= image_tag @user.avatar_url(:pre_crop), id: "cropbox" %>
<h4>Preview</h4>
<div style="width:100px; height:100px; overflow:hidden;">
<%= image_tag @user.avatar.url(:pre_crop), :id => "preview" %>
</div>
<%= form_for @user do |f| %>
<div class="actions">
<% %w[x y w h].each do |attribute| %>
<%= f.hidden_field "crop_#{attribute}"%>
<% end %>
<%= f.submit "Crop" %>
</div>
<% end %>