Skip to content

Instantly share code, notes, and snippets.

@mendes5
Created November 24, 2020 21:11
Show Gist options
  • Select an option

  • Save mendes5/c69e54fe29855454b33d681d6dcc4b7f to your computer and use it in GitHub Desktop.

Select an option

Save mendes5/c69e54fe29855454b33d681d6dcc4b7f to your computer and use it in GitHub Desktop.
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