I'm not able to display the correct highlighted square with jcrop in the preview div. I'm getting area which is not the same as the actual highlighted area, please check the screenshot below:
This is the code I have:
function updatePreview(c) {
if (parseInt(c.w) > 0) {
// Show image preview
var imageObj = jQuery("#imgcrop")[0];
var canvas = jQuery("#preview")[0];
var context = canvas.getContext("2d");
context.beginPath();
//context.arc(50, 50, 50, Math.PI * 2, 0, true); // you can use any shape
context.arc(50, 50, 50, Math.PI * 4, 0, true); // you can use any shape
context.clip();
context.closePath();
//context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, 100, 100);
context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, 100, 100);
}
};
function getcroparea(c) {
jQuery('.hdnx').val(c.x);
jQuery('.hdny').val(c.y);
jQuery('.hdnw').val(c.w);
jQuery('.hdnh').val(c.h);
};
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image = new Image();
var image_default = jQuery('#user-avatar').find('.default img');
//var image_edit = jQuery('#user-avatar').find('.edit img');
var image_edit = jQuery('#edit-image-form').find('.crop-image-side img');
reader.readAsDataURL(input.files[0]);
reader.onload = function (e) {
image.src = e.target.result;
image.onload = function () {
var width = this.width;
var value = (width - 154) / 2;
image_edit.css('left', '-' + value + 'px');
image_default.css('left', '-' + value + 'px');
};
//jQuery('#user-avatar').find('img').attr('src', image.src);
jQuery('#imgcrop').attr('src', image.src);
jQuery('#<%=hfImageData.ClientID %>').val(image.src);
jQuery('#imgcrop').Jcrop({
onSelect: getcroparea,
onChange: updatePreview,
aspectRatio: 1,
setSelect: [70, 25, 150, 150],
boxWidth: 0,
boxHeight: 0
});
}
}
}
Any idea what should I change to have the correct section highlighted?
Looks like your original image is resized via CSS or whatever and the Jcrop gets it's coordinates screwed up.
As described here, there are 2 methods to fix this:
with the boxWidth/boxHeight
options, which make Jcrop scale the image proportionally within the box dimensions
with the trueSize
option, usable when the height and width are already set on the image object in the DOM.
Setting the trueSize
to the image's naturalWidth
and naturalHeight
seems to work well.
Here's the JSFiddle
(note that the image is scaled via CSS, and check how Jcrop is initialized).