ユーザーが画像をアップロードするときに、画像をトリミングして、このトリミングがプレビューでどのように見えるかを確認できるように、Jcrop を実装しようとしています。
画像を引き伸ばして幅を歪めているように見えるプレビューを除いて、すべてが最終的に正常に機能しています。
私が持っている現在のコードは次のとおりです。
Crop.html.erb
<% content_for :head do %>
<script type="text/javascript" charset="utf-8">
$(function() {
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 300, 300],
aspectRatio: 1
});
});
function update_crop(coords) {
var rx = 100/coords.w;
var ry = 100/coords.h;
var lw = $('#cropbox').width();
var lh = $('#cropbox').height();
var ratio = <%= @user.avatar_geometry[:width] %> / lw ;
$('#preview').css({
width: Math.round(rx * lw) + 'px',
height: Math.round(ry * lh) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
$("#crop_x").val(Math.round(coords.x * ratio));
$("#crop_y").val(Math.round(coords.y * ratio));
$("#crop_w").val(Math.round(coords.w * ratio));
$("#crop_h").val(Math.round(coords.h * ratio));
}
</script>
<% end %>
<%= image_tag @user.avatar_url(:normal), :id => "cropbox" %>
<h3>Preview</h3>
<div class="preview">
<%= image_tag @user.avatar_url(:thumb), :id => "preview" %>
</div>
<%= form_for @user do |f| %>
<% for attribute in [:crop_x, :crop_y, :crop_h, :crop_w] %>
<%= f.hidden_field attribute, :id => attribute %>
<% end %>
<p><%= f.submit "Crop" %></p>
<% end %>
誰かが私が間違っている場所を知っていれば素晴らしいでしょう? よろしくお願いします。