From 044d373ddd9c450d06987acc12f74523d298b9d6 Mon Sep 17 00:00:00 2001 From: j1ngzoue Date: Mon, 18 Dec 2023 13:48:49 +0900 Subject: [PATCH] refactor: --- example/vite/src/App.tsx | 10 +++--- src/useAnimationTexture.ts | 69 +++++++++++++++++++++----------------- 2 files changed, 43 insertions(+), 36 deletions(-) diff --git a/example/vite/src/App.tsx b/example/vite/src/App.tsx index a8167d5..8a490dd 100644 --- a/example/vite/src/App.tsx +++ b/example/vite/src/App.tsx @@ -31,7 +31,7 @@ export default function App() { <> @@ -44,20 +44,20 @@ export default function App() { { load(url); }; -const drawPatch = ( - ctx: CanvasRenderingContext2D, - image: ImageData, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - frame: any -) => { - const dims = frame.dims; - const tempCanvas = document.createElement("canvas"); - tempCanvas.width = dims.width; - tempCanvas.height = dims.height; - const tempCtx = tempCanvas.getContext("2d"); - if (!tempCtx) { - return null; - } - tempCtx.putImageData(image, 0, 0); - ctx.drawImage( - tempCanvas, - 0, - 0, - dims.width, - dims.height, - dims.left, - dims.top, - dims.width, - dims.height - ); -}; - const initializeWorker = () => { if (!worker) { worker = new framesWorker(); @@ -108,7 +79,7 @@ const initializeWorker = () => { export const useAnimationTexture = ({ url, interval = DEFAULT_INTERVAL, - loop = DEFAULT_ENABLED_LOOP, + loop = DEFAULT_LOOP, autoplay = DEFAULT_AUTOPLAY, }: UseAnimationTextureArgs) => { const [animationTexture, setAnimationTexture] = @@ -117,6 +88,42 @@ export const useAnimationTexture = ({ const isGif = url.endsWith(".gif"); const needsDisposal = useRef(false); const [playing, setPlaying] = useState(autoplay); + const tempCanvas = useRef(null); + const tempCtx = useRef(null); + + const drawPatch = ( + ctx: CanvasRenderingContext2D, + image: ImageData, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + frame: any + ) => { + const dims = frame.dims; + if (!tempCanvas.current) { + tempCanvas.current = document.createElement("canvas"); + } + tempCanvas.current.width = dims.width; + tempCanvas.current.height = dims.height; + if (tempCtx.current) { + tempCtx.current = tempCanvas.current.getContext("2d"); + } + + if (!tempCtx.current) { + return null; + } + tempCtx.current.putImageData(image, 0, 0); + ctx.drawImage( + tempCanvas.current, + 0, + 0, + dims.width, + dims.height, + dims.left, + dims.top, + dims.width, + dims.height + ); + }; + const frameUpdate = useCallback(() => { const currentFrames = getFrameses(url); if (