From 51077e0b82298be83a888b32d98022fc48e92e32 Mon Sep 17 00:00:00 2001 From: Bernard Xie Date: Thu, 13 Apr 2023 13:40:58 -0700 Subject: [PATCH] Update generate_png.js --- lib/png/generate_png.js | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/png/generate_png.js b/lib/png/generate_png.js index 31cf1e439..9f4286da3 100644 --- a/lib/png/generate_png.js +++ b/lib/png/generate_png.js @@ -1,4 +1,4 @@ -async ({imgString, scale}) => { +async ({ imgString, scale }) => { const tempImg = new Image(); const loadImage = () => { return new Promise((resolve, reject) => { @@ -13,6 +13,31 @@ async ({imgString, scale}) => { const canvas = document.createElement("canvas"); canvas.width = img.width * scale; canvas.height = img.height * scale; + + // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas + const MAX_DIMENSION = 32767; + const MAX_AREA = 268435456; + + const ratio = img.width / img.height; + if (ratio > 1) { + if (canvas.width > MAX_DIMENSION) { + canvas.width = MAX_DIMENSION; + canvas.height = MAX_DIMENSION / ratio; + } + } else { + if (canvas.height > MAX_DIMENSION) { + canvas.height = MAX_DIMENSION; + canvas.width = MAX_DIMENSION * ratio; + } + } + + const currentArea = canvas.width * canvas.height; + if (currentArea > MAX_AREA) { + const areaRatio = MAX_AREA / currentArea; + canvas.height = Math.floor(canvas.height * areaRatio); + canvas.width = Math.floor(canvas.width * areaRatio); + } + const ctx = canvas.getContext("2d"); if (!ctx) { return new Error("could not get canvas context");