From 92a87a846d6bfbcccac514171d2b5219d3905259 Mon Sep 17 00:00:00 2001 From: Lim Chee Aun Date: Wed, 14 Jun 2023 11:15:05 +0800 Subject: [PATCH] Try use OffscreenCanvas for avatars --- src/components/avatar.jsx | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/components/avatar.jsx b/src/components/avatar.jsx index a9fef01d..a215c7bd 100644 --- a/src/components/avatar.jsx +++ b/src/components/avatar.jsx @@ -13,6 +13,11 @@ const SIZES = { const alphaCache = {}; +const canvas = window.OffscreenCanvas + ? new OffscreenCanvas(1, 1) + : document.createElement('canvas'); +const ctx = canvas.getContext('2d'); + function Avatar({ url, size, alt = '', squircle, ...props }) { size = SIZES[size] || size || SIZES.m; const avatarRef = useRef(); @@ -54,17 +59,11 @@ function Avatar({ url, size, alt = '', squircle, ...props }) { if (isMissing) return; try { // Check if image has alpha channel - const canvas = document.createElement('canvas'); - const ctx = canvas.getContext('2d'); - canvas.width = e.target.width; - canvas.height = e.target.height; + const { width, height } = e.target; + if (canvas.width !== width) canvas.width = width; + if (canvas.height !== height) canvas.height = height; ctx.drawImage(e.target, 0, 0); - const allPixels = ctx.getImageData( - 0, - 0, - canvas.width, - canvas.height, - ); + const allPixels = ctx.getImageData(0, 0, width, height); // At least 10% of pixels have alpha <= 128 const hasAlpha = allPixels.data.filter((pixel, i) => i % 4 === 3 && pixel <= 128) @@ -76,6 +75,7 @@ function Avatar({ url, size, alt = '', squircle, ...props }) { avatarRef.current.classList.add('has-alpha'); } alphaCache[url] = hasAlpha; + ctx.clearRect(0, 0, width, height); } catch (e) { // Silent fail alphaCache[url] = false;