简体   繁体   中英

Cropping an image with a preview using jcrop

I'm using jcrop and trying to make a "live" preview of the cropped area on an image.

The movement of the selected area works perfectly if the "Crop Selection" area is the same height and width as the destination preview div.

Check out the issue 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've commented out a few of my tests and attempts at getting this code to work properly but I just can't wrap my head around the relationship between the position and the size background properties in order to get this effect to work correctly.

Calculate the horizontal and vertical ratios between the selection size and the preview area size:

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

Then apply them to the 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 your jCrop selection area, it means you have scale the original image by 3, and compensate for the scaling when defining the background position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM