Skip to content

Instantly share code, notes, and snippets.

@OlivierJM
Created October 13, 2021 22:09
Show Gist options
  • Save OlivierJM/e296c846b88927b9371c422d8758cd95 to your computer and use it in GitHub Desktop.
Save OlivierJM/e296c846b88927b9371c422d8758cd95 to your computer and use it in GitHub Desktop.
const createImage = url => {
return new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener('load', () => resolve(image));
image.addEventListener('error', error => reject(error));
image.setAttribute('crossOrigin', 'anonymous');
image.src = url;
});
};
export const getCroppedImg = async (imageSrc, crop) => {
const image = await createImage(imageSrc);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
/* setting canvas width & height allows us to
resize from the original image resolution */
canvas.width = 450;
canvas.height = 116;
ctx.drawImage(image, crop.x, crop.y, crop.width, crop.height, 0, 0, canvas.width, canvas.height);
return new Promise(resolve => {
canvas.toBlob(blob => {
resolve(blob);
}, 'image/png');
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment