Skip to content
Related Articles

Related Articles

How to crop an image using canvas ?

View Discussion
Improve Article
Save Article
  • Last Updated : 21 Jun, 2020
View Discussion
Improve Article
Save Article

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.


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



<!DOCTYPE html>
        How to crop image
        using canvas?
    <h2>Source Image</h2>
    <img id="myImage" src=
    <h2>Cropped Image</h2>
    <canvas id="myCanvas" width="500" height="200" 
        style="border:3px solid">
        HTML5 canvas tag is not 
        supported by your browser.
        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);


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!