Open In App

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.



Syntax:

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

Example: 




<!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:


Article Tags :