Cropping image with preview with jcrop

I am using jcrop and trying to make a live preview of the cropped area in an image.

Selected area movement works fine if the Crop Select area is the same height and width as the target preview box.

Take a look here: http://jsfiddle.net/fbaAW/

function showCoords(c) 
{
    var $this = this.ui.holder;


    var original = $this.prev();
    var preview = original.parent().find(".image");

    var oH = original.height();
    var oW = original.width();

    var pH = preview.height();
    var pW = preview.width();

    var sH = c.h;
    var sW = c.w;

    var differenceH = pH - sH;
    var differenceW = pW - sW;


    //preview.css('width', c.w);
    //preview.css('height', c.h);

    //preview.css("background-size", Math.round(oW + differenceW) + "px" + " " + Math.round(oH + differenceH) + "px");

    preview.css("background-position", Math.round(c.x) * -1 + "px" + " " + Math.round(c.y) * -1 + "px");
}

      

As you can see, I commented out a few of my tests and tried to work correctly with this code, but I just cannot wrap around the relationship between position and size background properties for this effect to work correctly.

+3


source to share


1 answer


Calculate horizontal and vertical relationships between selection size and preview area size:

var rW = pW / c.w;
var rH = pH / c.h;

      

Then apply them to background-size

and background-position

:



preview.css("background-size", (oW*rW) + "px" + " " + (oH*rH) + "px");
preview.css("background-position", rW * Math.round(c.x) * -1 + "px" + " " + rH * Math.round(c.y) * -1 + "px");

      

http://jsfiddle.net/fbaAW/1/

So, if the preview size is, say, 3 times the size of the jCrop selection area, that means you are scaling the original image by 3 and compensating for the scaling when defining the background position.

+7


source







All Articles