1

The black image is appearing instead of showing a cropped image in my case. I have tried using image.onload as well. What could be the possible reason for this?

Code:


    const canvas = document.createElement('canvas');
    canvas.width = pixelCrop.width;
    canvas.height = pixelCrop.height;
    const ctx = canvas.getContext('2d');
    const newImage = new Image();

    ctx.drawImage(
      newImage,
      pixelCrop.x,
      pixelCrop.y,
      pixelCrop.width,
      pixelCrop.height,
      0,
      0,
      pixelCrop.width,
      pixelCrop.height
    );

    //image -- <img src='url'/>
    newImage.src = image.src;

    return new Promise((resolve, reject) => {
      canvas.toBlob((blob) => {
        console.log('blob is', blob);
        blob.name = fileName;
        window.URL.revokeObjectURL(this.fileUrl);
        this.fileUrl = window.URL.createObjectURL(blob);
        resolve(this.fileUrl);
      }, 'image/jpeg');
    });



screenshot

vam
  • 492
  • 7
  • 17
  • 1
    At the time drawImage is called, your image doesn't even have an src. Then, loading an image is asynchronous. So you'd have to wrap a image.onload part inside your Promise where you will draw the image and only then call toBlob. – Kaiido Jan 11 '19 at 14:20
  • Possible duplicate of [CanvasContext2D drawImage() issue \[onload and CORS\]](https://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors) – Kaiido Jan 11 '19 at 14:20
  • @Kaiido Could you please update my code! I am not getting the part you're suggesting here. – vam Jan 11 '19 at 15:27
  • 1
    https://jsfiddle.net/0yc6bdno/ – Kaiido Jan 12 '19 at 07:23
  • @Kaiido Do you know how we can save blob as an image such as uploading to s3 – vam Jan 21 '19 at 17:04

1 Answers1

1

Let image.onload complete and then generate the blob from the canvas. You can do something like this:

export const getCroppedImg = async (
  url: string, pixelCrop: {
    width: number,
    height: number,
    x: number,
    y: number
  }
): Promise<string> => {
  const canvas = document.createElement('canvas');
  canvas.width = pixelCrop.width;
  canvas.height = pixelCrop.height;
  const ctx = canvas.getContext('2d');

  const img = new Image;
  img.src = url

  return new Promise(resolve => {
    img.onload = () => {
      ctx?.drawImage(
        img,
        pixelCrop.x,
        pixelCrop.y,
        pixelCrop.width,
        pixelCrop.height,
        0,
        0,
        pixelCrop.width,
        pixelCrop.height
      );

      canvas.toBlob((file: any) => {
        resolve(URL.createObjectURL(file))
      }, 'image/jpeg')
    }
  })
Fabian
  • 188
  • 2
  • 5