Search code examples
javascriptjqueryhtmlimagecroppie

Using croppie to crop images without jquery


I am trying to add an image cropper to a website I am working on. The example I am basing it on is here:

https://jsfiddle.net/Twisty/afb76b7f/8/

The JS panel claims it is plain javascript, but it uses JQuery too ( if I am not wrong, not familiar with it at all ). I am trying to remove it, to keep the website as easy to maintain as possible, but I am getting an error.

HTML:

<div id="page">
    <div id="demo-basic">
    </div>
</div>

CSS:

#page
{
    background: #FFF;
    padding: 20px;
    margin: 20px;
}

#demo-basic {
  width: 200px;
  height: 300px;
}

JS

$(function() {
    var basic = $('#demo-basic').croppie ( {
        viewport: {
            width: 150,
            height: 150
        }
    });
    basic.croppie('bind', {
        url: 'https://i.imgur.com/xD9rzSt.jpg',
      });
});

So, from what I understand, the first $( function () ) can be simplified by calling the onLoad method, and $('demo-croppie' ) can be simplified by using document.getElementById ( 'demo-croppie' )

So, the page imports the croppie javascript files

croppie.js croppie.min.js

And tried to simplify the script like this ( onLoad event of page body )

var basic = document.getElementById('demo-basic').croppie({
    viewport: {    
        width: 150,
        height: 150
    }
});

basic.croppie('bind', {
    url: previewPictureSource,
}); 

But I get a reference error:

ReferenceError: croppie is not defined

I cannot find the croppie function anywhere, or understand how to associate it to an object.

Is there an obvious solution to this problem?

I am also happy to try any other library which crops image with a square resulting image, if anybody has more to suggest


Solution

  • You cannot call .croppie() on basic because you initialized it using VanillaJS. However, you can call .bind() on it directly:

    basic.bind({                                                                 
        url: previewPictureSource
    });
    

    The documentation specifies that you can interact with a Croppie object in the following two ways:

    // with jQuery
    $('#item').croppie(method, args);
    // with VanillaJS
    croppieObject.method(args);
    

    Check out the documentation here: https://foliotek.github.io/Croppie/