How to Resize an Image Using HTML Canvas in JavaScript?
The HTML <canvas> element is utilized to draw graphics in different aspects. It is useful for animation, plotting graphs, and combining photos. Moreover, users can resize the image by providing specific dimensions. It does not change the original image but creates a new cropped or resized image. For this purpose, the drawImage() method is utilized to scale the image in canvas elements.
The practical implementation of resizing the image is divided into two separate files, i.e., HTML and JavaScript.
HTML Code
The description of the code is provided here:
- First, an image URL is provided by specifying width and height with <img> tags.
- After that, HTML <canvas> is adjusted by resizing the width and height of the image.
- In the end, a JavaScript “test.js” is linked by providing the source.
JavaScript Code
var img = document.getElementById("fire");
var canvas = document.getElementById("can");
var context = canvas.getContext("2d");
context.drawImage(img, 10, 10);
};
In this JavaScript code:
- Firstly, the “window.onload” event is utilized for checking if the webpage is ready to display.
- After that, getElementById property is employed to extract the image and canvas ids by “fire” and “can”.
- After that, the getContext() method is used to show the drawing on canvas by passing a “2d” surface.
- In the end, the drawImage() method is utilized to draw a new image. Moreover, x and y coordinates are specified as “10” and “10” for placing the image on the canvas.
Output
The output shows that the full image is resized by applying the drawImage() method in the HTML <canvas>. The right portion of the above display represents the resized portion of the image.
Conclusion
JavaScript provides a drawImage() method to resize the image by employing the HTML <canvas>. The method takes input as the heights and widths of the existing image. After that, a resizing factor is applied to draw a new image based on the provided heights and widths. Moreover, users can specify the web images for resizing via JavaScript. In this post, users have learned to resize the image based on HTML <canvas>. It has various applications in online shopping stores, gaming sites, etc.