Digital images are composed of a two dimensional array as well as grid of vertical and horizontal pixels, small color squares each called pixel. Image cropping is a way of image editing that involves selecting a portion of an image, hence reducing the number of pixels and changing the aspect ratio as well as size. |
A canvas is a html element which is a white region in which you can display or draw graphical elements in modern web browsers. A common way to crop an image in JavaScript is with the HTML5 <canvas> element and then transform the images by calling the drawImage() function respectively. |
Step 1: Create a Canvas in HTML Create a <canvas> element in your HTML document using below code: <canvas id="mycanvas" width="800px" height="400px"></canvas> |
Step 2: Create a JavaScript File and a Crop Function Define a function named cropImage(), which you can call from within your code when an image loaded from some source or from base64 string. Add the onload() function to the Image object so that cropImage() runs only after an image is fully loaded on the viewer’s browser. onload() gets the <canvas> element from your HTML and then will prepare a 2D context object for the canvas. const canvas = document.getElementById('mycanvas'); const context = canvas.getContext('2d'); |
Step 3: Load the Image Create an image object from any source you want and load an image with the src property from a local drive or the internet or base64 string as per your requirement. var image = new Image(); image.src = "https://static.image.com/img.jpg"; |
Step 4: Call the drawImage() Function Here’s the syntax of the drawImage() function when Image object loaded: drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); Crop operations require all nine parameters described below:
image.onload = function() { context.drawImage(image, 100, 100, 200, 200, 50,50, 200, 200); } drawImage() performs two steps for further process:
|
Below is another solid example of how we can crop image:
const image = new Image(); image.crossOrigin='anonymous'; image.onload = () => { const canvas: any = document.createElement('canvas'); const ctx: any = canvas.getContext('2d'); canvas.height = image.naturalHeight - 25; // above line will crop out 25px from bottom canvas.width = image.naturalWidth; ctx.drawImage(image, 0, 0); const dataUrl: any = canvas.toDataURL(); // dataUrl is base64 encoded value of cropped image }; image.onerror = function() { alert("Failed to process image"); }; image.src = "https://static.image.com/hello.png"; |
Saturday, September 16, 2023
Cropping Images in JavaScript | Crop an Image in JavaScript With HTML Canvas
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment