JSFiddle - React, Tailwind, and code Playground
by denislexic
HTML
<link rel="stylesheet" href="http://odyniec.net/projects/imgareaselect/css/imgareaselect-default.css">
<script src="http://odyniec.net/projects/imgareaselect/jquery.imgareaselect.pack.js"></script>
<h2>Crop your image</h2><img id="profile_resizer_original_img" src="http://odyniec.net/projects/imgareaselect/ladybug.jpg" alt="Original image" width="250" />
<h4>This will be your avatar</h4><div id="profile_new_img_holder" style="width:100px; height:100px; overflow:hidden;"><img id="profile_future_img" src="http://odyniec.net/projects/imgareaselect/ladybug.jpg" alt="Preview image" /></div>
<br />
<form method="post" id="profile_avatar_resize_form">
<input type="hidden" name="x1" />
<input type="hidden" name="y1" />
<input type="hidden" name="x2" />
<input type="hidden" name="y2" />
<input type="hidden" name="w" />
<input type="hidden" name="h" />
<button type="submit" class="btn btn-primary">Save your new avatar</button>
</form>
JavaScript
$(document).ready(function () {
$('#profile_resizer_original_img').imgAreaSelect({
aspectRatio:'1:1',
handles:true,
onSelectChange:profile_img_resize,
onSelectEnd:function (image, selection) {
$('input[name=x1]').val(selection.x1);
$('input[name=y1]').val(selection.y1);
$('input[name=x2]').val(selection.x2);
$('input[name=y2]').val(selection.y2);
$('input[name=w]').val(selection.width);
$('input[name=h]').val(selection.height);
}
});
});
function profile_img_resize(img, selection) {
var scaleX = $('#profile_new_img_holder').width() / (selection.width || 1);
var scaleY = $('#profile_new_img_holder').height() / (selection.height || 1);
var original_img_width = $('#profile_resizer_original_img').width();
var original_img_height = $('#profile_resizer_original_img').height();
console.log("width: "+scaleX +", height: "+scaleY );
$('#profile_future_img').css({
width:Math.round(scaleX * original_img_width) + 'px',
height:Math.round(scaleY * original_img_height) + 'px',
marginLeft:'-' + Math.round(scaleX * selection.x1) + 'px',
marginTop:'-' + Math.round(scaleY * selection.y1) + 'px'
});
}