Skip to content
Related Articles
Open in App
Not now

Related Articles

How to crop an image using canvas ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 13 Feb, 2023
Improve Article
Save Article
Like 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 context = canvas.getContext("2d");
            var img = document.getElementById("myImage");
            context.drawImage(img, 10, 10,
                300, 175, 0, 0, 100, 175);


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!