How to fit image in canvas using cropperJS

7k Views Asked by At

I am new using cropperjs library. But I'm struggling on how can I configure it.

What I have
https://jsfiddle.net/kaeqxfjL/

What I need
I want to integrate a full image crop where you just need to drag the photo inside the canvas instead of having a square to crop the photo. I also need to make the width of the photo fit to the width of the canvas so you cannot drag it left/right; you could only drag it up/down.

var canvas  = $("#canvas"),
    context = canvas.get(0).getContext("2d"),
    $result = $('#result');

$('#fileInput').on( 'change', function(){
    if (this.files && this.files[0]) {
      if ( this.files[0].type.match(/^image\//) ) {
        var reader = new FileReader();
        reader.onload = function(evt) {
           var img = new Image();
           img.onload = function() {
             context.canvas.height = img.height;
             context.canvas.width  = img.width;
             context.drawImage(img, 0, 0);
             var cropper = canvas.cropper({
               aspectRatio: 16 / 9,
               dragMode: 'move'
             });
             
             $('#btnCrop').click(function() {
                // Get a string base 64 data url
                var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png"); 
                $result.append( $('<img>').attr('src', croppedImageDataURL) );
             });
             $('#btnRestore').click(function() {
               canvas.cropper('reset');
               $result.empty();
             });
           };
           img.src = evt.target.result;
                };
        reader.readAsDataURL(this.files[0]);
      }
      else {
        alert("Invalid file type! Please select an image file.");
      }
    }
    else {
      alert('No file(s) selected.');
    }
});
/* Limit image width to avoid overflow the container */
img {
  max-width: 100%; /* This rule is very important, please do not ignore this! */
}

#canvas {
  height: 290px;
  width: 650px;
  background-color: #ffffff;
  cursor: default;
  border: 1px solid black;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.3/cropper.css" rel="stylesheet"/>





<p>
<!-- Below are a series of inputs which allow file selection and interaction with the cropper api -->
        <input type="file" id="fileInput" accept="image/*" />
        <input type="button" id="btnCrop" value="Crop" />
        <input type="button" id="btnRestore" value="Restore" />
</p>
<div>
  <canvas id="canvas">
    Your browser does not support the HTML5 canvas element.
  </canvas>
</div>      

<div id="result"></div>
        




<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.3/cropper.js"></script>

1

There are 1 best solutions below

2
On

Set image width using class:

.img-container img {
      width: 100%;
    }

And set viewMode and aspectRatio as below.

var cropper = canvas.cropper({
                aspectRatio: 16 / 9,
                dragMode: 'move',
                viewMode: 3,
                aspectRatio: 1
              });

var canvas = $("#canvas"),
  context = canvas.get(0).getContext("2d"),
  $result = $('#result');

$('#fileInput').on('change', function() {
  if (this.files && this.files[0]) {
    if (this.files[0].type.match(/^image\//)) {
      var reader = new FileReader();
      reader.onload = function(evt) {
        var img = new Image();
        img.onload = function() {
          context.canvas.height = img.height;
          context.canvas.width = img.width;
          context.drawImage(img, 0, 0);
          var cropper = canvas.cropper({
            aspectRatio: 16 / 9,
            dragMode: 'move',
            viewMode: 3,
            aspectRatio: 1

          });

          $('#btnCrop').click(function() {
            // Get a string base 64 data url
            var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png");
            $result.append($('<img>').attr('src', croppedImageDataURL));
          });
          $('#btnRestore').click(function() {
            canvas.cropper('reset');
            $result.empty();
          });
        };
        img.src = evt.target.result;
      };
      reader.readAsDataURL(this.files[0]);
    } else {
      alert("Invalid file type! Please select an image file.");
    }
  } else {
    alert('No file(s) selected.');
  }
});
/* Limit image width to avoid overflow the container */

img {
  max-width: 100%;
  /* This rule is very important, please do not ignore this! */
}

#canvas {
  height: 290px;
  width: 650px;
  background-color: #ffffff;
  cursor: default;
  border: 1px solid black;
}

.img-container img {
  width: 100%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.3/cropper.css" rel="stylesheet" />





<p>
  <!-- Below are a series of inputs which allow file selection and interaction with the cropper api -->
  <input type="file" id="fileInput" accept="image/*" />
  <input type="button" id="btnCrop" value="Crop" />
  <input type="button" id="btnRestore" value="Restore" />
</p>
<div>
  <canvas id="canvas" class="img-container">
    Your browser does not support the HTML5 canvas element.
  </canvas>
</div>

<div id="result"></div>





<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.3/cropper.js"></script>