1

I want to get the Blob value of an Canvas without Promise. The reason for this is, that I cannot change the outer code and there is no way to wait for the Promise to complete. Using a Promise will raise the problem, that all outer functions will need to use them, too.

I'm already inside a function where the FormData is submitting and this is my last change to inject an image into the already collected FormData.

I found a synchronous way, using the toDataUrl function (side question: is there ANY reason, why this function is synchronous and toBlob is not?).

This is my approach:

public getBlob(dataType?: string, quality?: number): Blob {
  let dataUrl: string = this.canvas.toDataURL(dataType, quality)
  let i: number;
  let byteString: string;
  let mimeString: string;
  let ia: Uint8Array;

  if(dataUrl.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(dataUrl.split(',')[1]);
  else
    byteString = unescape(dataUrl.split(',')[1]);

  mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
  ia = new Uint8Array(byteString.length);

  for(i = 0; i < byteString.length; i++)
    ia[i] = byteString.charCodeAt(i);

  return new Blob([ia], {type: mimeString});
}

Is there any better and/or faster way to resolve this task?

SuperNova
  • 2,792
  • 2
  • 25
  • 34
  • Have you read this question? [which function should I use? .toDataURL() or .toBlob()?](https://stackoverflow.com/q/59020799/1426891) It indicates the hazards of `toDataURL`. It's hard to tell from the part of the problem you've seen, but in your position I would try to stop the form submission using `preventDefault` and then programmatically submit the form when the data is available. It's more work up front, but investing in a synchronous API could mean a synchronous performance problem you can't escape without a rewrite. – Jeff Bowman Sep 28 '22 at 19:48

0 Answers0