Skip to content

Instantly share code, notes, and snippets.

@manute
Last active January 31, 2016 14:12
Show Gist options
  • Save manute/5574989 to your computer and use it in GitHub Desktop.
Save manute/5574989 to your computer and use it in GitHub Desktop.
Cropping js with jCrop
$(function(){
var CropImage = {
id:'crop_image',
$modal_cropping : $('#modalCroopingImage'),
$div_cropping:$('#cropping'),
jcrop_api:"",
original : {
width: 0,height: 0,url: "",uuid: ""
},
destroyJcrop : function(){
if(this.jcrop_api!=="") this.jcrop_api.destroy();
},
initialize : function(){
this.original.width = $('#originalPhotoWidth').val();
this.original.height = $('#originalPhotoHeight').val();
this.original.url = $('#originalPhotoUrl').val();
this.original.uuid = $('#originalPhotoUuid').val();
}
};
function jcropImage(){
CropImage.destroyJcrop();
$('#'+CropImage.id).attr("src", CropImage.original.url);
$('#'+CropImage.id).css('width',CropImage.original.width +'px');
$('#'+CropImage.id).css('height',CropImage.original.height +'px');
$('#'+CropImage.id).Jcrop({
setSelect: [0, CropImage.original.height/2, CropImage.original.height/2, 0],
minSize: [100, 100],
onSelect: updateCoords,
onChange: updateCoords,
bgColor: 'white',
aspectRatio: 1 //square
},function(){ CropImage.jcrop_api = this;});
}
function updateCoords(coords) {
$('#x').val(coords.x);
$('#y').val(coords.y);
$('#w').val(coords.w);
$('#h').val(coords.h);
var rx = 100 / coords.w;
var ry = 100 / coords.h;
var width = rx * CropImage.original.width;
var height = ry * CropImage.original.height;
$('#currentImage').css({
width: Math.round(width) + 'px',
height: Math.round(height) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
$('#uploadPhotoJcrop').on('click',function(event){
event.preventDefault();
Cropping.initialize();
jcropImage();
});
function coordsAndData(){
return {
dimension_x:$('#x').val(),
dimension_y:$('#y').val(),
dimension_w:$('#w').val(),
dimension_h:$('#h').val(),
current_photo: $('#current_photo').val(),
original_photo: $('#original_photo').val()
};
}
$('#confirm_photo').live('click',function(event){
event.preventDefault();
$.ajax({
url: 'urlControllerConfirmImage',
type:'POST',
cache: false,
data: coordsAndData(),
dataType: "json",
success: function(data){
$('#modalCroopingImage').modal('hide');
},
error: function(request, status, error) {
console.log(error);
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment