Crop Image using Javascript (Croppie)

Akrramo picture Akrramo · Dec 3, 2015 · Viewed 10.4k times · Source

I am trying to crop an image to cicle using the Croppie Library

I have tried to use their functions to return base64 encoded image. And it return a base64 code but without the image: Here is my code:

<div id="vanilla-demo"></div>
 </div>
<img id="myImage" src="">

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="croppie.js"></script>

<script type="text/javascript">


        var vanilla = new Croppie(document.getElementById('vanilla-demo'), {
            viewport: { width: 200, height: 200 , type:'circle'},
            boundary: { width: 400, height: 400 },
            showZoom: false
        });
        vanilla.bind('dac.jpg');
            vanilla.result('canvas','original').then(function (src) {
                    console.log(src);
                    $('#myImage').attr('src', src);
            });

</script>

Answer

Dustin Smith picture Dustin Smith · Jan 4, 2016

I'm one of the creators of Croppie. With a quick glance at your code, I'd say that your croppie isn't bound yet. The bind method returns a Promise that you'll need to wait to be resolved. The Promise waits for the image to load and all of the initialization logic to finish on the Croppie.

I would change your bind and result logic to do the following instead:

vanilla.bind('dac.jpg').then(function() {
    vanilla.result('canvas','original').then(function (src) {
        console.log(src);
        $('#myImage').attr('src', src);
    });
});