From a45ca2a607f891eff8295ff8b97ced1236ce4e29 Mon Sep 17 00:00:00 2001 From: bydooweedoo Date: Thu, 27 Feb 2014 23:41:43 -0800 Subject: [PATCH] Fix image ratio while cropping --- lib/assets/javascripts/papercrop.js | 42 ++++++++++++++++++----------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/lib/assets/javascripts/papercrop.js b/lib/assets/javascripts/papercrop.js index aeb2d27..9a31f1e 100644 --- a/lib/assets/javascripts/papercrop.js +++ b/lib/assets/javascripts/papercrop.js @@ -1,15 +1,27 @@ (function ($) { - window.jcrop_api = null; - window.init_papercrop = function() { + var win = window; + + win.jcrop_api = null; + + win.init_papercrop = function() { $("div[id$=_cropbox]").each(function() { var attachment = $(this).attr("id").replace("_cropbox", ""); - var preview = !!$("#" + attachment + "_crop_preview").length; - var aspect = $("input#" + attachment + "_aspect").val(); - var width = $(this).width(); + preview = !!$("#" + attachment + "_crop_preview").length, + aspect = $("input#" + attachment + "_aspect").val(), + ratio = 1.0, + width = $(this).width(), + boxWidth = $("input[id$='_" + attachment + "_box_w']").val(); + + if (boxWidth > width) { + boxWidth = width; + $("input[id$='_" + attachment + "_box_w']").val(boxWidth); + ratio = $('input[id$="_' + attachment + '_original_w"]').val() / width; + } + + var update_crop = function(coords) { - update_crop = function(coords) { var preview_width, rx, ry; if (preview) { @@ -21,15 +33,15 @@ $("img#" + attachment + "_crop_preview").css({ width : Math.round(rx * $("input[id$='_" + attachment + "_original_w']").val()) + "px", height : Math.round((ry * $("input[id$='_" + attachment + "_original_h']").val()) / aspect) + "px", - marginLeft : "-" + Math.round(rx * coords.x) + "px", - marginTop : "-" + Math.round((ry * coords.y) / aspect) + "px" + marginLeft : "-" + Math.round(rx * coords.x * ratio) + "px", + marginTop : "-" + Math.round((ry * coords.y * ratio) / aspect) + "px" }); } - $("#" + attachment + "_crop_x").val(Math.round(coords.x)); - $("#" + attachment + "_crop_y").val(Math.round(coords.y)); - $("#" + attachment + "_crop_w").val(Math.round(coords.w)); - $("#" + attachment + "_crop_h").val(Math.round(coords.h)); + $("#" + attachment + "_crop_x").val(Math.round(coords.x * ratio)); + $("#" + attachment + "_crop_y").val(Math.round(coords.y * ratio)); + $("#" + attachment + "_crop_w").val(Math.round(coords.w * ratio)); + $("#" + attachment + "_crop_h").val(Math.round(coords.h * ratio)); }; $(this).find("img").Jcrop({ @@ -37,15 +49,13 @@ onSelect : update_crop, setSelect : [0, 0, 250, 250], aspectRatio : aspect, - boxWidth : $("input[id$='_" + attachment + "_box_w']").val() + boxWidth : boxWidth }, function() { jcrop_api = this; }); }); }; - $(document).ready(function() { - init_papercrop(); - }); + $(document).ready(init_papercrop); }(jQuery));