Search code examples
jqueryhtmlcssjcrop

CSS: display preview for cropped image


I am cropping an image using Jcrop and I am getting the coordinates. I want to display preview for the cropped part upon clicking on "Preview" button. I am not sure how can I achieve that.


Solution

  • Here's one way of doing it following their thumbnail example with some deviations.

    $(function () {
        var $target = $('#target'),
            $preview = $('#preview');
        // hold the coordinates of the cropped image
        var coords;
        // initialize the widget
        $target.Jcrop({
            // save the coordinates of the cropped image after selecting
            onSelect: function (c) {
               coords = c;
            }
        });
        // when a button is clicked, show preview of the cropped image using the saved coordinates 
        $('button').on('click', function () {
            // make a copy of the image with the original dimensions
            var $img = $('<img/>', {
                src: $target[0].src,
                css: {
                  position: 'absolute',
                  left: '-' + Math.round(coords.x) + 'px',
                  top: '-' + Math.round(coords.y) + 'px',
                  width: $target.css('width'),
                  height: $target.css('height')
                }
            });
            // set the dimensions of the preview container
            $preview.css({
                position: 'relative',
                overflow: 'hidden',
                width: Math.round(coords.w) + 'px',
                height: Math.round(coords.h) + 'px'
            });
            // add+position image relative to its container 
            $preview.html($img);
        });
    });
    

    Here's a demo.