Search code examples
javascriptjquerycssimagecrop

How to avoid transparent background using cropping plugin


I'm using this cropping tool https://github.com/fengyuanchen/cropper/. I have this issue, that if I add an image dynamically there is some transparent background around the image. So the image does not fit the container and it also makes it possible to crop around the image. I followed the examples on the docs to try to get rid of the transparent background, but with no success.

here is my code:

<div id="imgWrap" style="max-height:400px;min-height:400px">
    <img id="img" src="" /> // Image gets added dynamically
</div>

the javascript

var reader = new FileReader(); 
reader.onloadend = function () {

var img = $('#imgWrap img');
img.attr('src', reader.result);

img.cropper({
    aspectRatio: 1 / 1,
    autoCropArea: 0.65,
    guides: false,
    strict: true,   
    highlight: false,
    responsive:true,
    dragCrop: false,
    movable: true,
    resizable: true,
    zoomable: true,
    touchDragZoom:true,
    rotatable: false,
    minCropBoxWidth:105,
    minCropBoxHeight:105,
    built: function () {
        // cropper-container is the element where the image is placed
        $('.cropper-container').cropper('setCanvasData', {
            left: 0,
            top: 0,
            width: 700,
            height: 700
           }
        );                                      
    },
})

I tried to this: https://github.com/fengyuanchen/cropper#setcanvasdatadata but nothing happens

You can see an example here:

enter image description here

The natural size of the image is 1920x1200

This is what is generated after the image is added: enter image description here

So, does anyone have a suggestion how to get rid of the transparent background and make the image fit the container?


Solution

  • I had the exact same issue. In the Cropper doc it says to set the img max-width = 100%. I did this and it fixed the issue

    https://github.com/fengyuanchen/cropper

    /* Limit image width to avoid overflow the container */
    img {
      max-width: 100%; /* This rule is very important, please do not ignore this! */
    }