Open In App

How to Crop an Image Using Canvas?

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Cropping an image using an HTML5 canvas involves selecting a specific portion of an image and displaying only that part on the canvas. This technique is useful for focusing on a particular area of an image, removing unwanted sections, or fitting images into specific layouts without altering the original file.

Approach

In this approach, we will create an HTML structure with an image element and a canvas element. The image element (`<img>`) displays the source image, while the canvas element (`<canvas>`) is used to show the cropped portion of the image. When the web page loads, a JavaScript function executes, which first retrieves the canvas element and its 2D drawing context. It then obtains the image element. The `drawImage` method of the canvas context is used to draw a specific portion of the image onto the canvas. The method's parameters define the cropping coordinates and dimensions from the source image (starting at x=10, y=10, width=300, height=175) and where to place this cropped portion on the canvas (starting at x=0, y=0, width=100, height=175). This results in a cropped version of the original image being displayed within the canvas element.

Syntax:

drawImage(image, sourceX, sourceY, sourceW, sourceH, 
destinationX,destinationY, destinationW, destinationH)

Parameters:

  • image: The image to be cropped.
  • sourceX: The x-coordinate of the source image
  • sourceY: The y-coordinate of the source image.
  • sourceW: The width of the source image.
  • sourceH: The height of the source image.
  • destinationX: The x-coordinate of the destination image.
  • destinationY: The y-coordinate of the destination image.
  • destinationW: The width of the destination image.
  • destinationH: The height of the destination image.

Example: This example shows the implementation of the above-explained approach.

javascript
<!DOCTYPE html>
<html>

<head>
    <title>
        How to crop image
        using canvas?
    </title>
</head>

<body>

    <h2>Source Image</h2>
    <img id="myImage" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200615165012/double_quotes.jpg"
        alt="GeeksForGeeks">

    <h2>Cropped Image</h2>

    <canvas id="myCanvas" width="500" height="200" style="border:3px solid">
        HTML5 canvas tag is not
        supported by your browser.
    </canvas>

    <script>
        window.onload = function () {
            let canvas = document.getElementById("myCanvas");
            let context = canvas.getContext("2d");
            let img = document.getElementById("myImage");

            context.drawImage(img, 10, 10,
                300, 175, 0, 0, 100, 175);
        }
    </script>
</body>

</html>

Output:


Similar Reads