From d52e8fdb144cc3077f0d0afa4008f103c0da657f Mon Sep 17 00:00:00 2001 From: Sam Becker Date: Fri, 1 Mar 2024 13:16:31 -0600 Subject: [PATCH] Prevent unnecessary blur calculation --- src/components/CanvasBlurCapture.tsx | 56 +++++++++++++++------------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/src/components/CanvasBlurCapture.tsx b/src/components/CanvasBlurCapture.tsx index 54540a79..3bdd6d98 100644 --- a/src/components/CanvasBlurCapture.tsx +++ b/src/components/CanvasBlurCapture.tsx @@ -25,39 +25,43 @@ export default function CanvasBlurCapture({ }) { const refCanvas = useRef(null); const refTimeouts = useRef([]); + const refShouldCapture = useRef(true); useEffect(() => { const capture = () => { - const canvas = refCanvas.current; - if (canvas) { - canvas.width = width * scale; - canvas.height = height * scale; - canvas.style.width = `${width}px`; - canvas.style.height = `${height}px`; - const context = refCanvas.current?.getContext('2d'); - if (context) { - context.scale(scale, scale); - context.filter = - 'contrast(1.2) saturate(1.2)' + - `blur(${scale * 10}px)`; - context.drawImage( - image, - -edgeCompensation, - -edgeCompensation, - width + edgeCompensation * 2, - width * image.height / image.width + edgeCompensation * 2, - ); - refTimeouts.current.forEach(clearTimeout); - onCapture(canvas.toDataURL('image/jpeg', quality)); + if (refShouldCapture.current) { + const canvas = refCanvas.current; + if (canvas) { + canvas.width = width * scale; + canvas.height = height * scale; + canvas.style.width = `${width}px`; + canvas.style.height = `${height}px`; + const context = refCanvas.current?.getContext('2d'); + if (context) { + context.scale(scale, scale); + context.filter = + 'contrast(1.2) saturate(1.2)' + + `blur(${scale * 10}px)`; + context.drawImage( + image, + -edgeCompensation, + -edgeCompensation, + width + edgeCompensation * 2, + width * image.height / image.width + edgeCompensation * 2, + ); + refTimeouts.current.forEach(clearTimeout); + onCapture(canvas.toDataURL('image/jpeg', quality)); + refShouldCapture.current = false; + } else { + console.error('Cannot get 2d context'); + // Retry capture in case canvas is not available + refTimeouts.current.push(setTimeout(capture, RETRY_DELAY)); + } } else { - console.error('Cannot get 2d context'); + console.error('Cannot generate blur data: canvas not found'); // Retry capture in case canvas is not available refTimeouts.current.push(setTimeout(capture, RETRY_DELAY)); } - } else { - console.error('Cannot generate blur data: canvas not found'); - // Retry capture in case canvas is not available - refTimeouts.current.push(setTimeout(capture, RETRY_DELAY)); } };