resize and crop image with canva in javascript

To resize and crop an image using canvas in Javascript, we first need to create a canvas element and load the image into it. Once the image is loaded, we can use the drawImage() method to draw it onto the canvas. Then, we can use the canvas.width and canvas.height properties to set the size of the canvas and the context.drawImage() method to resize and crop the image to the desired size.

Here's an example code:

index.tsx
// Load image into canvas
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
  // Set canvas size
  canvas.width = 200;
  canvas.height = 200;
  
  // Draw image onto canvas
  context.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
  
  // Get resized image data
  var resizedImageData = canvas.toDataURL('image/jpeg', 0.8);
  console.log(resizedImageData);
};
img.src = 'image.jpg';
500 chars
18 lines

In this example, we create a canvas element, load an image into it, set its size to 200x200 pixels, and draw the image onto the canvas while resizing and cropping it to fit the canvas size. Finally, we use the canvas.toDataURL() method to get the resized image data in JPEG format.

gistlibby LogSnag