From 74f3b3f13df4d703787af1f39806f70582e33b3e Mon Sep 17 00:00:00 2001 From: relaxtakenotes <91839650+relaxtakenotes@users.noreply.github.com> Date: Sun, 5 Jun 2022 10:18:07 +0500 Subject: [PATCH] fix: image width not being set properly (#143) * Fix image width not being set properly Sometimes it got set to 0 because the original image wasn't loaded yet. * fix: eslint Co-authored-by: dicedtomato <35403473+diced@users.noreply.github.com> --- src/pages/[...id].tsx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/pages/[...id].tsx b/src/pages/[...id].tsx index 0ffc86f..99ec9c8 100644 --- a/src/pages/[...id].tsx +++ b/src/pages/[...id].tsx @@ -32,16 +32,16 @@ export default function EmbeddedImage({ image, user, pass }) { const updateImage = async (url?: string) => { const imageEl = document.getElementById('image_content') as HTMLImageElement; - const original = new Image; - original.src = url || dataURL('/r'); - + const img = new Image(); + img.addEventListener('load', function() { + if (this.naturalWidth > innerWidth) imageEl.width = Math.floor(this.naturalWidth * Math.min((innerHeight / this.naturalHeight), (innerWidth / this.naturalWidth))); + else imageEl.width = this.naturalWidth; + }); + + img.src = url || dataURL('/r'); if (url) { imageEl.src = url; - } - - // Sometimes gives blank image on first load - if (original.width > innerWidth) imageEl.width = Math.floor(original.width * Math.min((innerHeight / original.height), (innerWidth / original.width))); - else imageEl.width = original.width; + }; }; useEffect(() => {