PNG image with transparent background giving black background on canvas with drawImage and putImageData

Viewed 27

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

0 Answers
Related