Guides
Last Updated Apr 11, 2024

How to Crop Images in JavaScript

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Image Processing API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Crop an Image Using Croppr.js

While it is possible to build your own vanilla javascript image cropper, we don't recommend doing so. Why? There are plenty of libraries out there today that can handle this task for you - many of them written in vanilla JS.

One vanilla javascript image cropper is Croppr.js, a lightweight image cropping library, written in 100% native JS. It is a pure javascript version of an image cropper with no dependencies that will bloat your package size or require constant maintenance and upgrades.

Let’s send your first free
API
Image Processing API
call
See why the best developers build on Abstract
Get your free api

How to Crop an Image Using Croppr.js

Let's take a look at how to use Croppr.js to crop images in your own application.

Get Started

Install the package using the command line:



npm install croppr --save

And include the files in your project. You can link to them in the <head> section of your HTML document, or, if you use a bundler, include them at the top of the file you use them in. Let's assume in this tutorial that you are using a module bundler and ES6 syntax.



import Croppr from 'croppr';

Create a New Croppr Instance

The Coppr package exports a Cropper object that can be instantiated to access the various methods and values, as seen in the following code snippet:



const cropper = new Croppr('#canvas-element', { #options });

Once you have the cropper instance, you can use it to grab the cropped value from the canvas element that was passed to the cropper:



const croppedValue = cropper.getValue();
# {x: Number, y: Number, width: Number, height: Number }

The image data object contains the x and y values of where the cropped version of the image starts and ends within the original image, plus the new width and height of the cropped version of the image.

Options

Croppr.js allows you to restrain or adjust the scope of the crop using options. One such option is a configurable aspect ratio that allows you to constrain the aspect ratio to whatever you'd like (1:1 or square crop, for example.)

To constrain the crop to a square, pass the aspectRatio option to the Croppr object upon instantiation:



var croppr = new Croppr('#canvas-element', {
  aspectRatio: 1
});

Other options include a maxSize and minSize that prevent a user from cropping the image beyond a particular size. There are also onCropStart, onCropMove, and onCropEnd callback functions that allow you to process the cropped version of the image in response to changes in the cropping region.

How to Crop an Image in JavaScript Using AbstractAPI

For an easier and even more lightweight solution, use an API to handle your image cropping. An image cropping API accepts an image file, or link to a hosted image file, and some parameters dictating how the image should be cropped. The API crops the image for you based on the provided parameters, and returns either the new image file, or a link to a new image, hosted in a bucket somewhere.

Let's look at how to crop an image using the Abstract API Free Image Processing and Optimization API.

Get Started

Go to the Abstract API homepage and click on the blue "Get Started" button.

You will be asked to sign up using an email address and password. If you have signed up before, you may be asked to log in. The API is completely free and you will never be spammed with emails or requests to upgrade your tier.

The free tier allows up to 100MB of uploads per month at one request/minute. The next tier-up gives you 1GB of uploads for $9 per month.

Once you're in, you’ll find the API dashboard. There, you'll find your API key, plus links to documentation, pricing, and support.

API Requests

AbstractAPI has two endpoints for image manipulation: one that accepts an image file through multipart form upload, and one that accepts an image URL for a hosted image. In this tutorial, we'll use the URL endpoint.

The endpoint accepts an HTTP POST with an object containing the source image data and our desired cropping specifications.

AbstractAPI processes the image and sends back a JSON object containing a new URL that points to the resized image. All images are hosted in Abstract API's secure Amazon S3 buckets.

Let's crop this image:

https://s3.amazonaws.com/static.abstractapi.com/test-images/dog.jpg”

Specify the Crop Area

AbstractAPI accepts crop parameters as part of the resize options. To specify how you want the given image cropped, make sure to set the strategy option to "crop" and indicate the width and height of the final cropped image.



resize: {
		"width": 100,
		"height: 75,
		"strategy": "crop",
		"crop_mode": "tl",
		"scale": 50
	}

You can also scale the cropped image (i.e. resize it) using a number that will be interpreted as a percentage. The crop_mode option allows you to specify which area of the original image you want to crop. By default, this will be set to center. Passing "tl" will constrain the crop to the "top left" corner of the image. Other options include "tr", "r", "l" and can also be specified as cardinal directions.

See the documentation for a full list of cropping options.

Receive the Cropped Image

AbstractAPI returns a JSON object. The object contains a URL to the new image, hosted at one of AbstractAPI's S3 buckets, plus information about the source image and the new image.

The JSON object looks like this:



{
   "original_size":205559,
   "original_height":430,
   "original_width":1142,
   "final_size":75101,
   "bytes_saved":130458,
   "final_height":75,
   "final_width":100,
   "url":"https://abstractapi-images.s3.amazonaws.com/8f2dd6392c524bc98313a89a24012b1f_dog.jpg"
}

4.3/5 stars (7 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Image Processing API
API
key now
Try Abstract's free Image Optimization API today!
get started for free

Related Articles

Get your free
API
Image Processing API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required