From c8c4ba5894f9ac383601044769e318f998c16669 Mon Sep 17 00:00:00 2001 From: Adrien Burgun Date: Mon, 27 Feb 2023 23:17:11 +0100 Subject: [PATCH] :bug: Batch render into one call, cache the ImageData between renders, scale pixels on big devices --- src/Simulation.tsx | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/Simulation.tsx b/src/Simulation.tsx index 4389e8c..3aac8d6 100644 --- a/src/Simulation.tsx +++ b/src/Simulation.tsx @@ -57,11 +57,8 @@ export default function Simulation() { const canvas2 = canvas(); if (!canvas2) return; - draw(canvas2, updateState(width(), height())); - // setTimeout(() => { - window.requestAnimationFrame(frame); - // }, 100); + window.requestAnimationFrame(frame); } window.requestAnimationFrame(frame); @@ -84,9 +81,11 @@ export default function Simulation() { } } + const downscale = window.devicePixelRatio ** 2 * window.innerWidth * window.innerHeight > 2000000 ? 16 : 8; + return @@ -96,7 +95,7 @@ export default function Simulation() { height: '100dvh', background: '#202024' }} - downscale={8} + downscale={downscale} onAttach={setCanvas} onDetach={() => setCanvas(undefined)} @@ -108,16 +107,19 @@ export default function Simulation() { ; } +let imageData: ImageData = undefined as unknown as ImageData; + function draw(canvas: HTMLCanvasElement, state: State) { const context = canvas.getContext('2d')!; const width = state.width; const height = state.height; - context.clearRect(0, 0, canvas.width, canvas.height); - const buffer = state.get(); - const imageData = context.getImageData(0, 0, canvas.width, canvas.height); + if (imageData?.width !== canvas.width || imageData?.height !== canvas.height) { + imageData = context.getImageData(0, 0, canvas.width, canvas.height); + } + imageData.data.fill(0); function set(x: number, y: number, r: number, g: number, b: number, a: number) { const offset = (y * canvas.width + x) * 4;