Created
October 5, 2020 08:42
-
-
Save LironHazan/b9816164186910b54a669d6c908ad850 to your computer and use it in GitHub Desktop.
a try I did..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function renderImage(ctx, url, width, height): Promise<boolean> { | |
return new Promise((resolve) => { | |
fetch(url) | |
.then((res) => res.blob()) | |
.then((blob) => createImageBitmap(blob)) | |
.then((ibm) => { | |
ctx.drawImage(ibm, 0, 0); | |
resolve(); | |
}); | |
}); | |
} | |
export class InlineWorkerHelper { | |
/** | |
* Inline worker workaround of running web workers from within an Angular lib | |
* Returns an instance of the worker | |
*/ | |
static run(task: (ctx, url, width, height) => Promise<boolean>, offscreen: any, imgUrl, width, height): Worker { | |
// if (!(usrCode instanceof Function)) { | |
// return; | |
// } | |
const code = `const renderImage = ${task}; | |
self.onmessage = ({ data }) => { | |
if (data.id !== 'export_png') { return; } | |
renderImage(data.canvas.context, data.imgUrl, data.width, data.height).then(result => self.postMessage(result, null)) | |
};`; | |
const blob = new Blob([code], { type: 'application/javascript' }); | |
const url = URL.createObjectURL(blob); | |
const worker = new Worker(url); | |
worker.postMessage( | |
{ id: 'export_png', action: 'init', canvas: offscreen, imgUrl, width, height }, | |
[offscreen] // the transformed canvas | |
); | |
return worker; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment