ashutosh ashutosh - 4 years ago 315
Javascript Question

JCrop How to crop image by dragging it behing a div (like facebook cover)

I have used Jcrop extensively but I want to crop the image in much similar way the Facebook uses for cropping its cover image.

So, I want a div to be of some fixed size wherein the background to hold a draggable image of its original size, which the user drag and find the suitable visible region to be cropped.

From what I have learnt, in JCrop, the original image is of fixed size and draggable region moves over it which you want to be cropped.I just want the opposite. The image to be draggable and selection region to be fixed.

Is there a way to do it using JCrop?

Answer Source

I have been searching this for a while, While I got another great plugin- JWindowCrop

Also you can get plugin from the repository.

It is benefitial for the fact that the plugin is quite simple and you can easily modify it as per your needs.

Here is how I did it to match the crop area of facebook cover:

HTML:

<img id="target" class="crop" alt="" src="images/sample-cover.jpg" />

JavaScript:

$('.crop').jWindowCrop({
                targetWidth: 851, //Width of facebook cover division
                targetHeight: 315, //Height of cover division
                loadingText: 'Your Cover is uploading....',
                onChange: function(result) {
                    console.log("separation from left- "+result.cropX);
                    console.log("separation from top- "+result.cropY);
                    console.log("width- "+result.cropW);
                    console.log("Height- "+result.cropH);
                }
            });

You can modify the internal region if you are not satisfies with the plugin.

NOTE: Since the facebook cover is of width 851px only, the uploaded image and the cropper division must be of same width i.e 851px.

I have prepared a DEMO here

EDIT: Just in case if you noticed the text "Drag to reposition" in the crop area(top-left side) while you drag the image inside cover, you can mention you own text by changing this line of plugin:

 Line:34-   base.$frame.append('<div class="jwc_controls" style="position:relative;display:'+(base.options.showControlsOnStart ? 'block' : 'none')+';"><span class="dragger">Drag to reposition</span></div>');

I could not got time to add an option in the plugin to do so.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download