Warm tip: This article is reproduced from stackoverflow.com, please click
css html jquery jcrop

jcrop attaches only one time

发布于 2020-03-31 22:55:32

I need to perform client side cropping.

To do that i'm using jcrop.

Now, since my cropping surface needs to fit in a modal i did the following: (read below or the code directly)

When there is a change in the input, i destroy any jcrop element and remove all css tags from my image except max-"width:100%" so that the image does not overflow.

Then the file from the input gets assigned in a image tag. After that the modal is shown so that i can get the width and height of the properly sized image element.

I then assign these dimensions to the boxWidth and boxHeight parameters of jcrop and attach it to the image so that the jcrop element does not overflow either. I had to place the code around it inside the fileReader.onload function so that it would take dimensions only after the source for the image was changed.

$(document).on('change', '#upload', function (evt) {
        var tgt = evt.target || window.event.srcElement,
            files = tgt.files;
        $('.jcrop-holder').remove();
        $('#studentPhoto').css("width", "");
        $('#studentPhoto').css("height", "");
        $('#studentPhoto').css("visibility", "");
        $('#studentPhoto').css("display", "");

        // FileReader support
        if (FileReader && files && files.length) {
            var fr = new FileReader();
            var w;
            var h;
            fr.onload = function () {
                $('#studentPhoto').attr('src', fr.result)
                $('#imgMOD').show('fast', '', function () {
                    w = $('#studentPhoto').width();
                    h = $('#studentPhoto').height();
                    $('#studentPhoto').Jcrop({
                        onSelect: showCoords,
                        aspectRatio: 667 / 500,
                        boxWidth: w,
                        boxHeight: h
                    });
                });


            }
            fr.readAsDataURL(files[0]);
        }

        function showCoords(c) {
            $('#x').text(c.x);
            $('#y').text(c.y);
            $('#x2').text(c.x2);
            $('#y2').text(c.y2);
            $('#w').text(c.w);
            $('#h').text(c.h);
        };
    });

Problem is, even though the debugger shows that the .jcrop part is reached it will not create a jcrop element afer the second itteration. First time it works perfectly.

Questioner
MrNutbutters
Viewed
19
MrNutbutters 2020-01-31 19:22

Ok so Jcrop i don't know how this is different but this way of removing Jcrop solves the problem.

if ($('#studentPhoto').data('Jcrop')) {
                    $('#studentPhoto').data('Jcrop').destroy();}