Created
November 24, 2020 21:11
-
-
Save mendes5/c69e54fe29855454b33d681d6dcc4b7f to your computer and use it in GitHub Desktop.
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
| export const urlToImageFile = (url: string, { backgroundColor = '#000' }): Promise<File> => { | |
| const image = new Image(); | |
| const promise = new Promise<File>((resolve, reject) => { | |
| image.addEventListener('load', function () { | |
| const canvas = document.createElement('canvas'); | |
| canvas.width = this.width; | |
| canvas.height = this.height; | |
| const context = canvas.getContext('2d'); | |
| if (!context) { | |
| reject(new Error('Canvas2D not supported'); | |
| return; | |
| } | |
| context.fillStyle = backgroundColor; | |
| context.fillRect(0, 0, this.width, this.height); | |
| context.drawImage(this, 0, 0); | |
| canvas.toBlob((blob) => { | |
| if (!blob) { | |
| reject(new Error('Failed to build blob')); | |
| return; | |
| } | |
| const file = new File([blob], 'share.png', { type: 'image/png' }); | |
| resolve(file); | |
| }, 'image/png'); | |
| }); | |
| image.addEventListener('error', () => { | |
| reject(new Error('Failed to load the image')); | |
| }); | |
| }); | |
| image.src = url; | |
| return promise; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment