2

I'm uploading the function here

const createImage = (url) =>
  new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener("load", () => resolve(image));
    image.addEventListener("error", (error) => reject(error));
    image.setAttribute("crossOrigin", "anonymous");
    image.src = url;
  });

function getRadianAngle(degreeValue) {
  return (degreeValue * Math.PI) / 180;
}

export default async function getCroppedImg(imageSrc, pixelCrop, rotation = 0) {
  const image = await createImage(imageSrc);
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  const maxSize = Math.max(image.width, image.height);
  const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2));

  canvas.width = safeArea;
  canvas.height = safeArea;

  ctx.translate(safeArea / 2, safeArea / 2);
  ctx.rotate(getRadianAngle(rotation));
  ctx.translate(-safeArea / 2, -safeArea / 2);

  ctx.drawImage(
    image,
    safeArea / 2 - image.width * 0.5,
    safeArea / 2 - image.height * 0.5
  );

  const data = ctx.getImageData(0, 0, safeArea, safeArea);

  canvas.width = pixelCrop.width;
  canvas.height = pixelCrop.height;

  ctx.putImageData(
    data,
    0 - safeArea / 2 + image.width * 0.5 - pixelCrop.x,
    0 - safeArea / 2 + image.height * 0.5 - pixelCrop.y
  );
  return canvas;
}

This is the original image: https://drive.google.com/file/d/1r5fHjYswsG89OkViN6-9EmmLP8BnojE5/view?usp=sharing

This is the image after this function is called: https://firebasestorage.googleapis.com/v0/b/ekko-development.appspot.com/o/dor3m3%2FYDW9hT0nJjhaP7uOoCpFO2Jzd6B3%2Fsocial%2Fimages_gallery%2Fbe1014?alt=media&token=8b30521f-196b-4c1b-a5b5-aea3d6e1f898

Shourya Shikhar
  • 1,342
  • 1
  • 11
  • 29
  • What's the expected output? In this case `putImageData` is applying the image on top of the default background which is black. If you want to match the background pattern seen in the first image, then you would have to literally draw it to the canvas before doing rest of the work. – Juho Vepsäläinen Sep 08 '22 at 16:50
  • I tried changing the background color using fill style method, and also by dom manipulating the canvas. but this isnt working. I just want to change the color to white – Shourya Shikhar Sep 08 '22 at 16:55
  • Ah, check here: https://stackoverflow.com/a/27736313/228885 . – Juho Vepsäläinen Sep 08 '22 at 18:30

0 Answers0