Easy Client Side Image Cropping Library – Cropper.js

Category: Image , Javascript | September 9, 2019
Author:oscarkey
Views Total:7,700 views
Official Page:Go to website
Last Update:September 9, 2019
License:MIT

Preview:

Easy Client Side Image Cropping Library – Cropper.js

Description:

Cropper.js is a tiny, simple-to-use JavaScript library which provides fast, touch-enabled, client-side image cropping based on Html5 <canvas>.

How to use it:

Import the library js file into your html page.

<script type="text/javascript" src="cropper.js"></script>

Create an html5 canvas element which cropper will draw on.

<canvas id="testCanvas" width="600" height="450">
  Your browser does not support canvas.
</canvas>

Create a series of inputs which allow file selection and interaction with the cropper api.

<input type="file" id="fileInput" onchange="handleFileSelect()" />
<input type="button" onclick="cropper.startCropping()" value="Start cropping" />
<input type="button" onclick="cropper.getCroppedImageSrc()" value="Crop" />
<input type="button" onclick="cropper.restore()" value="Restore" />

The JavaScript to active the cropper.

// initialize cropper by providing it with a target canvas and a XY ratio (height = width * ratio)
cropper.start(document.getElementById("testCanvas"), 1); 
      
function handleFileSelect() {
  // this function will be called when the file input below is changed
  var file = document.getElementById("fileInput").files[0];  // get a reference to the selected file
  
  var reader = new FileReader(); // create a file reader
  // set an onload function to show the image in cropper once it has been loaded
  reader.onload = function(event) {
    var data = event.target.result; // the "data url" of the image
    cropper.showImage(data); // hand this to cropper, it will be displayed
  };
  
  // this loads the file as a data url calling the function above once done
  reader.readAsDataURL(file); 
}

Changelog:

09/09/2019

  • add touchscreen support and fixing bugs with window scroll

You Might Be Interested In:


One thought on “Easy Client Side Image Cropping Library – Cropper.js

  1. Ghifary Ilham

    Hallo, i try this plugin to crop and it’s work
    but, how can i take the new name file input form the crop result

    if my file input name get from the result size is not like crop result

    Reply

Leave a Reply