How to crop an image using canvas ?

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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 contex = canvas.getContext("2d");
            var img = document.getElementById("myImage");
              
            contex.drawImage(img, 10, 10, 
                300, 175, 0, 0, 100, 175);
        }
    </script>
</body>
  
</html>

chevron_right



Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.