From 96133895c00f70cac60a785cc6416122804f2e05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Youn=20M=C3=A9lois?= Date: Sat, 9 Nov 2024 21:42:19 +0100 Subject: [PATCH] feat: compress images for smoother scrolling --- src/pages/Browse/ExtensionBrowse.tsx | 37 +++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/pages/Browse/ExtensionBrowse.tsx b/src/pages/Browse/ExtensionBrowse.tsx index 72cc490..5bdc43a 100644 --- a/src/pages/Browse/ExtensionBrowse.tsx +++ b/src/pages/Browse/ExtensionBrowse.tsx @@ -113,12 +113,47 @@ const MangaItem = ( const { ref, inView } = useInView(); const [src, setSrc] = useState(null); + const compressBlob = async (src: string, size: number) => + await new Promise((resolve) => { + const image = new Image(); + image.src = src; + image.onload = () => { + if (image.width <= size && image.height <= size) { + resolve(src); + return; + } + + const aspectRatio = image.width / image.height; + + let width, height; + if (image.width < image.height) { + width = size; + height = Math.round(width / aspectRatio); + } else { + height = size; + width = Math.round(height * aspectRatio); + } + + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + + const ctx = canvas.getContext("2d"); + ctx?.drawImage(image, 0, 0, width, height); + + const url = canvas.toDataURL("image/jpeg", 0.7); + resolve(url); + }; + }); + useEffect(() => { fetch(manga.coverUrl) .then((response) => response.blob()) .then((blob) => { const url = URL.createObjectURL(blob); - setSrc(url); + compressBlob(url, 300).then((url) => { + setSrc(url); + }); }); }, []);