crop image with canva to 1500 width and 800 height in javascript

You can use the HTML5 canvas element to crop an image to a specific width and height. Here's an example function in JavaScript using the Canva library:

index.tsx
function cropImage(url, width, height) {
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.crossOrigin = 'anonymous'; // use if image is hosted on another domain
  img.onload = function() {
    // calculate aspect ratio
    const aspectRatio = img.width / img.height;
    // calculate new crop dimensions
    const cropWidth = img.width > img.height ? img.height * aspectRatio : img.width;
    const cropHeight = img.height > img.width ? img.width / aspectRatio : img.height;
    // center crop
    const x = (img.width - cropWidth) / 2;
    const y = (img.height - cropHeight) / 2;
    // draw cropped image onto canvas
    ctx.drawImage(img, x, y, cropWidth, cropHeight, 0, 0, width, height);
    // get cropped image as data URL
    const dataURL = canvas.toDataURL();
    // do whatever you want with the dataURL (e.g. display as an image)
  };
  img.src = url;
}
991 chars
25 lines

This function takes three arguments: the URL of the image to crop, the desired width, and the desired height. It creates a new canvas element with the specified dimensions and then uses the drawImage method of the context to draw the cropped portion of the input image onto the canvas. The resulting cropped image can then be saved as a data URL for further use.

gistlibby LogSnag