client-side image cropping by cropperjs

5902   23 January 2020

Cropperjs is a feature-rich javascript library for cropping images, Using this you can able to crop an image on graphical interface and get that cropped image in the form of html canvas, whch is further convertable to Data URL and Blob.

Features:

it packed with several fetures that helps you to provide better cropping exprience to the client. but I'm talking about some important features only.

  • Touch Supported (Mobile)
  • Zooming Supported
  • Scaling Supported (flipping)
  • Multiple Cropping Supported
  • Cropping on Canvas Supported
  • it Supports 39 Options, 27 Methods, 6 Events
  • Cross-Browser Support

To use Cropperjs image cropper in your project you need to include cropperjs to your project.

Installation:

npm

npm install cropperjs

or For Browser (CDN)

<link href='https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.min.css' rel='stylesheet'>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.min.js'></script> 

After installing cropperjs and including it to the document, Let's play with cropperjs.

Instantiating Cropperjs Class

new Cropper(element[, options])
  • element - element that has to cropped, type of HTMLImageElement or HTMLCanvasElement.
  • options -  Options for cropping image, type of Object.

Example:

HTML

<div>
  <img id="image" src="picture.jpg">
</div>

Javascript

// Select Image for cropping
const image = document.getElementById('image');
// Instantiate Cropperjs by passing image element and some options.
const cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
});
// To get Cropped Canvas use getCroppedCanvas() method
let cropedData = cropper.getCroppedCanvas();
// To convert cropped data to Blob toBlob() method
let croppedImgBlob = cropedData.toBlob();
// To convert cropped data to Data URL toDataURL() method
let croppedImgDataURL = cropedData.toDataURL();


View More

Related Elements