I have created a system where a user will upload an image, it's resized to a certain width and then the user can crop the image (was using imgAreaSelect but upgraded to Jcrop to add mobile usage).
I have this all working fine. Once the user moves the selector of Jcrop to where they want and chooses the save button I have jQuery write some fancy CSS to show the portion of the image the user wants (the rest is hid via overflow: hidden
) plus more form to add photo credit and other information about the photo.
This again, works great... on a desktop. The image is full size on a mobile device and isn't responsive so you cannot see the majority of the photo. I've been trying to wrap my head around this for a while now (other than disabling the preview photo). Is there any way to get my method responsive?
$(document).on('click','#save-image',function() {
//$('img.mobimg').imgAreaSelect({remove:true});
//$('#the-image').fadeOut();
//Write the preview image using variables from image selector.
$('#the-image').fadeOut().html('<div align="center"><div id="img" style="position: relative; width: '+$('#w').val()+'px; height: '+$('#h').val()+'px; overflow: hidden;">'+
'<img src="'+theimg+'" id="finished-image" style="position: absolute; top: -'+$('#y1').val()+'px; left: '+$('#x1').val()+'px;">'+
'</div></div><hr>').fadeIn(function() { $('#finished-image').addClass('img-responsive'); });
// Fade in form to allow user to finish adding details.
$('.form-finish').fadeIn();
// Fade in main form submit button to allow user to submit the completed form.
$('.panel-footer').fadeIn(); // Final Submit Button to Fade In
jcrop_api.destroy();
});
Using CSS to trim the image worked fine for desktops that were wider than the image itself but when responsively resizing the image it's almost impossible due to the always changing widths and heights of the image depending on the device.
Instead; I turned to JavaScript that actually trims the image to the width and height and the location wanted, set out by the Jcrop which then has no issue using img-responsive
to resize the image to the mobile device.
function showPart(img, offsetTop, offsetLeft, width, height){
var src = img.src;
$(img).replaceWith("<canvas id='cnvs' class='img-responsive' style='max-width:100%;'></canvas>");
var canvas = document.getElementById('cnvs');
canvas.height = height;
canvas.width = width;
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
ctx.drawImage(this, offsetLeft, offsetTop, width, height, 0, 0, width, height);
};
img.src = src;
}
Original answer containing this snippet: https://stackoverflow.com/a/36436245/956106