Skip to content

Instantly share code, notes, and snippets.

@FormerlyZeroCool
Last active April 29, 2023 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FormerlyZeroCool/26c7817186d607d2a90f7f49c48104ce to your computer and use it in GitHub Desktop.
Save FormerlyZeroCool/26c7817186d607d2a90f7f49c48104ce to your computer and use it in GitHub Desktop.
export function sleep(ms:number):Promise<void> {
return new Promise<void>((resolve:any) => setTimeout(resolve, ms));
}
export async function crop(image:HTMLImageElement, x:number, y:number, width:number, height:number, image_type:string = "image/png", recurs_depth:number = 0):Promise<HTMLImageElement>
{
const canvas = document.createElement("canvas");
if(image && image.height && image.width)
{
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext("2d")!;
ctx.drawImage(image, x, y, width, height, 0, 0, width, height);
const res:HTMLImageElement = new Image();
res.src = canvas.toDataURL(image_type, 1);
return res;
}
else if(recurs_depth < 100)
{
await sleep(5);
return await crop(image, x, y, width, height, image_type, recurs_depth + 1);
}
else
{
throw "Exception: timeout waiting to parse image data in render";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment