Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to crop images in ReactJS ?
Next article icon

How to Crop an Image in JavaScript?

Last Updated : 08 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To crop an image in JavaScript, you can use the <canvas> element to manipulate the image's dimensions and crop it to a specified area. This approach is flexible and works entirely in the browser without needing external libraries. Here's a step-by-step example demonstrating how to crop an image using JavaScript:

Example for Cropping an Image with Canvas

HTML
<!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>Crop Image with JavaScript</title> </head> <body>   <input type="file" id="fileInput" accept="image/*">   <canvas id="canvas" style="border: 1px solid black;"></canvas>   <script>     const fileInput = document.getElementById('fileInput');     const canvas = document.getElementById('canvas');     const ctx = canvas.getContext('2d');      fileInput.addEventListener('change', function() {       const file = fileInput.files[0];       const reader = new FileReader();        reader.onload = function(event) {         const img = new Image();         img.onload = function() {           // Set canvas dimensions to desired crop size           const cropWidth = 100; // Desired width of cropped image           const cropHeight = 100; // Desired height of cropped image           canvas.width = cropWidth;           canvas.height = cropHeight;            // Calculate crop position (example: top-left corner)           const cropX = 50; // Starting x-coordinate           const cropY = 50; // Starting y-coordinate            // Draw the cropped portion of the image on the canvas           ctx.drawImage(img, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);         };         img.src = event.target.result;       };        if (file) {         reader.readAsDataURL(file);       }     });   </script> </body> </html> 

Output:

Screenshot-2024-11-08-125848
Choose Image
Screenshot-2024-09-13-163908
Original Image
Screenshot-2024-11-08-130006
Cropped Image


Explanation:

  1. File Input: The <input type="file"> element allows users to select an image from their device.
  2. Reading the Image: A FileReader object reads the selected image file and converts it to a data URL, which can be used as the src of an Image object.
  3. Loading the Image: Once the image is loaded, the canvas dimensions are set to the desired crop size.
  4. Cropping: The drawImage() method of the canvas context (ctx) is used to crop and draw the specified portion of the image. It takes several parameters:
    • img: The image to draw.
    • cropX and cropY: The starting coordinates of the crop area within the source image.
    • cropWidth and cropHeight: The dimensions of the crop area.
    • 0, 0, cropWidth, cropHeight: The coordinates and dimensions to draw the cropped portion on the canvas.

Key Points:

  • drawImage() Method: This method is key to cropping. The first four parameters specify the source image and crop area, while the last four parameters specify the destination coordinates and size on the canvas.
  • Canvas Resizing: Setting the canvas dimensions controls the size of the cropped output.
  • Flexible Cropping: You can adjust cropX, cropY, cropWidth, and cropHeight to crop different areas of the image.

This approach provides a simple way to crop images in the browser using only JavaScript and <canvas>. It's efficient for image manipulation tasks and does not require any server-side processing


Next Article
How to crop images in ReactJS ?

A

anuragtriarna
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to create an image map in JavaScript ?
    An image map is nothing but an image that is broken into various hotspots and each hotspot will take you to a different file. Hotspots are nothing but clickable areas which we create on an image by using the <area> tag. This type of map is called a client-side image map as the map is embedded
    3 min read
  • How to Display Images in JavaScript ?
    To display images in JavaScript, we have different approaches. In this article, we are going to learn how to display images in JavaScript. Below are the approaches to display images in JavaScript: Table of Content Using CreateElementUsing InnerHTMLApproach 1: Using CreateElementIn an HTML document,
    2 min read
  • How to Make an SVG Image in JavaScript ?
    The SVG images are vector images that do not lose their quality either in the case of Zoom in or Zoom out. These are the Scalable Vector Graphics that can be directly created using the <svg> tag in HTML or dynamically using JavaScript. Let us create an SVG using JavaScript. We can use the belo
    2 min read
  • How to crop images in ReactJS ?
    Image cropping is a common requirement in web applications, especially when dealing with user-generated content, photo editing, or image manipulation. ReactJS, being a popular JavaScript library for building user interfaces, provides various techniques and libraries that can be used to implement ima
    3 min read
  • How to use document.images in JavaScript ?
    In JavaScript, the document.images property returns a collection of all "<img>" elements within the current document. We can manipulate these images using various properties and methods. We will see how to work with document.images in JavaScript. ApproachFirst, create a basic HTML structure an
    2 min read
  • How to Create an Image Element using JavaScript?
    We will dynamically create an <img> element in HTML using JavaScript. When a button is clicked, we'll generate the <img> element and append it to the document. Using createElement() methodCreate an empty img element using document.createElement() method.Then set its attributes like (src,
    1 min read
  • How to pass image as a parameter in JavaScript function ?
    We all are familiar with functions and their parameters and we often use strings, integers, objects, and arrays as a parameter in JavaScript functions but now will see how to pass an image as a parameter in the JavaScript functions. We will use vanilla JavaScript here. Approach: First, create a func
    2 min read
  • How to Crop Image in CSS?
    Cropping images using CSS is an effective way to display only a portion of the image without altering the image file itself. Cropping can allow the designers to focus on the specific parts of the image while maintaining control over how the image fits within the layout. 1. Using overflow PropertyThi
    2 min read
  • How to zoom-in and zoom-out image using JavaScript ?
    Zooming in and out of images using JavaScript refers to the ability to increase (zoom in) or decrease (zoom out) the size of an image interactively. This effect enhances user experience by allowing users to focus on specific image details or view the full image easily. These are the following ways:
    3 min read
  • How to convert image into base64 string using JavaScript ?
    In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript. ApproachHere we will create a gfg.js file which will include JavaScript code and one gfg.html file.Now we will put onchang
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences