How to Crop an Image in JavaScript Using HTML Canvas?
The canvas is a blank area in which the user can perform any task regarding the image. JavaScript provides the drawImage() method for cropping an image. The method is utilized to scale an image into canvas elements. This method works the same as rectangular by specifying the size and location of the image.
The syntax of the drawImage() method is provided below:
Syntax
The parameters are explained as below:
Parameters Description
img | Specifies the image (via the <img> tag) to be cropped and displayed in the browser. |
src_x | Specifies the start of cropping of the source image from the x-axis. |
src_y | Denotes the start of the cropping of the source image from the y-axis. |
sWid | Identifies the width of the image. |
sHei | Represents the height of the image. |
dx | Specifies the started point from the x-axis for drawing. |
dy | Specifies the started point from the y-axis for drawing. |
dWid | Represents the width of the image to be displayed. |
dHei | Represents the height of the image to be displayed. |
Let us practice the drawImage() method to crop an image using HTML canvas in JavaScript.
Example
An example is considered to crop an image in JavaScript by employing the HTML canvas. The example consists of HTML and JavaScript code sections. These sections are discussed as follows.
HTML Code
The description of the code is as follows:
- An <img> tag is utilized by specifying dimensions containing width and height.
- A URL of a web image is assigned to src.
- After that, the HTML canvas element is utilized to display the cropped image in the browser.
- In the end, the JavaScript file test.js is linked within <script> tags.
JavaScript Code
var img = document.getElementById("flower");
var canvas = document.getElementById("can_id");
var context = canvas.getContext("2d");
context.drawImage(img, 10, 10);
};
In this code:
- Firstly, the “window.onload” event is employed to check whether the webpage is ready to display.
- Furthermore, the getElementById property is utilized to extract the image and canvas id by “flower” and “can_id”.
- After that, the getContext() method is used to show the drawing on canvas as a “2d” surface.
- Finally, the drawImage() method is employed for drawing a new image. Moreover, x and y coordinates are passed as “10” and “10” for placement of the image on the canvas.
Output
The output shows that the full image is resized by applying the drawImage() method in the browser window.
Conclusion
In JavaScript, the drawImage() method is utilized with three arguments to crop an image by utilizing the HTML canvas element. The method accepts a variety of arguments, but only the image-reference, height, and width are utilized to crop an image. The getElementById also plays a key role in retrieving the image element. This article demonstrates various methods to crop an image in JavaScript using HTML canvas.