Crop Images In Javascript (Simple Examples)

Welcome to a tutorial on how to crop images in Javascript. Want to lessen the server load by cropping the image on the client side? Or just curious about how those “online image crop tools” work?

To crop an image in Javascript:

  1. Create an image and canvas.
    • var img = new Image();
    • var canvas = document.createElement("canvas");
    • var ctx = canvas.getContext("2d");
  2. On image load, “crop” by copying a part of the source image onto the canvas – img.onload = () => { ctx.drawImage(img, SX, SY, SWIDTH, SHEIGHT, DX, DY, DWIDTH, DHEIGHT); };
  3. Set the image source to start – img.src = "SOURCE.JPG";

That covers the basics, read on for an actual example!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/crop-images-javascript/” title=”How To Crop Images In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT CROP IMAGE

All right, let us now get into the examples of how to crop an image in Javascript.

 

EXAMPLE 1) SIMPLE IMAGE CROP

1-simple.html
<!-- (A) HTML CANVAS -->
<canvas id="demo" width="300" height="300"></canvas>
 
 <script>
// (B) SOURCE IMAGE OBJECT
var img = new Image();
 
// (C) CROP ON LOAD
img.onload = () => {
  // (C1) GET CANVAS + 2D CONTEXT
  let canvas = document.getElementById("demo"),
  ctx = canvas.getContext("2d");
 
  // (C2) CROP BY COPYING PART OF SOURCE IMAGE TO CANVAS
  ctx.drawImage(img,
    // SOURCE X, Y, WIDTH, HEIGHT
    50, 100, 300, 300,
    // DESTINATION X, Y, WIDTH, HEIGHT
    0, 0, 300, 300
  );
};
 
// (D) GO!
img.src = "easter.png";

This is the “full version” of the introduction snippet, I think the confusion mostly lies with the “crop” – We are not actually doing a crop, but copying a part of the source image onto the canvas. Just what are those SX, SY, SWIDTH, SHEIGHT, DX, DY, DWIDTH, DHEIGHT? I will let this explain itself:

 

 

EXAMPLE 2) PICK IMAGE & CROP

2-pick-crop.html
<!-- (A) FILE PICKER -->
<input type="file" id="picker" accept="image/jpeg,image/png,image/webp"/>
 
 <script>
// (B) AUTO START ON SELECT FILE
let picker = document.getElementById("picker");
picker.onchange = () => {
  // (C) CREATE CANVAS
  let canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d");
  canvas.width = 300;
  canvas.height = 300;

  // (D) CREATE ANCHOR + SELECTED IMAGE URL
  let anchor = document.createElement("a"),
      surl = URL.createObjectURL(picker.files[0]);
 
  // (E) CREATE IMAGE + CROP
  let img = new Image();
  img.onload = () => {
    // (E1) DO YOUR OWN CROP CALCULATIONS...
    ctx.drawImage(img, 50, 100, 300, 300, 0, 0, 300, 300);
 
    // (E2) "FORCE DOWNLOAD"
    anchor.href = canvas.toDataURL("image/png");
    anchor.download = "cropped.png";
    anchor.click(); // MAY NOT WORK - BETTER TO LET USER CLICK
 
    // (E3) CLEAN UP
    anchor.remove();
    canvas.remove();
    img.remove();
    URL.revokeObjectURL(surl);
  };
 
  // (F) GO!
  img.src = surl;
};

This is for you guys who are looking to do the “conventional pick file, crop, and download”. Not going to explain this line-by-line, but it essentially does the same “simple crop” – Except that we have to jump through a lot of hoops to read the selected image file, and to “force a download”.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

The examples should work on all modern browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

How To Crop Images In Javascript (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *