Search code examples
javascripthtmlcsscropcropperjs

cropper doesn't load in img element in a modal


I'm using fengyuanchen's cropper to crop an uploaded image and then post it to form.

<div id="change-dp" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <button class="uk-modal-close-outside" type="button" uk-close></button>
            <h2 class="uk-modal-title">Change Profile Picture</h2><br>
            <form action="{{url_for('upload_dp', username=username)}}" method="POST" enctype="multipart/form-data">
            <input type="file" accept="image/*" placeholder="Upload profile picture" onchange="loadFile(event)" id="uploaded" required>
            <img id="dp" onchange=""/>
                    
            <div id="cropped"></div>

            <button type="submit">Upload</button>
            </form>
        </div>
    </div>

Javascript

var cropper;

function loadFile(image) {
    var dp = document.getElementById('dp')
    dp.src = URL.createObjectURL(image.target.files[0]);
    dp.onload = function() { URL.revokeObjectURL(dp.src)};
    cropper = new Cropper(dp, { aspectRatio: 1 });
};

The idea is that once the user uploads an image, it is rendered with a cropper, on submit, I'll generate cropped data into cropped div with js and submit that as a dp to server. I'm unable to get a display of cropper.

I do not use jquery in which most documentation is.

JSFiddle


Solution

  • It looks like you load cropper script untrusted domain site & forgot to load the css file as well. Here is the official CDN link: https://cdnjs.com/libraries/cropperjs

    // CSS
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.7/cropper.css" integrity="sha512-AuLN6bHjJzqZ+Iw48+GdQPp5uKBdPX6+zWV37ju9zw7XIrevIX01RsLtpTU/zCoQcKrQRPe/EpwDpZiv7OUYMA==" crossorigin="anonymous" />
    
    // Script
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.7/cropper.min.js" integrity="sha512-N4T9zTrqZUWCEhVU2uD0m47ADCWYRfEGNQ+dx/lYdQvOn+5FJZxcyHOY68QKsjTEC7Oa234qhXFhjPGQu6vhqg==" crossorigin="anonymous"></script>