Open In App

How to crop an image using canvas ?

Last Updated : 13 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The HTML canvas element allows the user to draw graphics on any web page. It is like a container for graphics to draw the graphics, JavaScript is used in the code.

<canvas id="Canvas1" width="100" height="100"></canvas>

Following are the attributes to create a canvas. More optional attributes can also be added. The canvas is referred in JavaScript by its id.

drawImage() method: This method can be used to draw an image or video on the web page. It can also be used to draw parts of an image. Another useful function is to increase or decrease the size of the image.

Cropping an image using drawImage() method: In order to crop a source image to its destination image. the following parameters of drawImage() need to be specified.

  • 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.

Syntax:

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

Example: 

javascript




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to crop image
        using canvas?
    </title>
</head>
 
<body>
 
    <h2>Source Image</h2>
    <img id="myImage" src=
        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 () {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            var img = document.getElementById("myImage");
             
            context.drawImage(img, 10, 10,
                300, 175, 0, 0, 100, 175);
        }
    </script>
</body>
 
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads