vam
vam

Reputation: 502

Black image is getting returned from canvas.toBlob

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

Upvotes: 1

Views: 1446

Answers (1)

Fabian
Fabian

Reputation: 318

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')
    }
  })

Upvotes: 1

Related Questions