Is there any way to handle canvas.toBlob with observables in rxjs?

Viewed 50

I've been trying to handle canvas.toBlob with observables in rxjs instead of promise or callbacks. bindCallback operator seems to fit so I've tried like:

bindCallback(canvas.toBlob)().pipe(
  map((blob: Blob) => URL.createObjectURL(blob))
);

but it gives me ERROR TypeError: Illegal invocation error.

If the operator doesn't fit, any other idea for this? Appreciate any insight. Thanks.

1 Answers

The problem is that the function canvas.toBlob loses the invocation context.

You'd have the same issue if you try this:

const toBlob = canvas.toBlob;

toBlob(blob => console.log('hello'));
// ERROR TypeError: Illegal invocation

this function, toBlob is internally using this, but as you're not calling it from an object this is undefined.

Solution is to bind it to the original canvas:

bindCallback(canvas.toBlob.bind(canvas))().pipe(
  map((blob: Blob) => URL.createObjectURL(blob))
);
Related