initial commit
This commit is contained in:
83
src/hooks/useGetOverviewSnapshot.ts
Normal file
83
src/hooks/useGetOverviewSnapshot.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { useRef, useCallback, useEffect } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
const apiUrl = import.meta.env.VITE_BASEURL;
|
||||
|
||||
async function fetchSnapshot(cameraSide: string) {
|
||||
const response = await fetch(
|
||||
`http://100.116.253.81/Colour-preview`
|
||||
//`${apiUrl}/${cameraSide}-preview`
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Cannot reach endpoint");
|
||||
}
|
||||
return await response.blob();
|
||||
}
|
||||
|
||||
export function useGetOverviewSnapshot(cameraSide: string) {
|
||||
const latestUrlRef = useRef<string | null>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const imageRef = useRef<HTMLImageElement | null>(null);
|
||||
|
||||
const drawImage = useCallback(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas?.getContext("2d");
|
||||
const img = imageRef.current;
|
||||
|
||||
if (!canvas || !ctx || !img) return;
|
||||
|
||||
canvas.width = canvas.clientWidth;
|
||||
canvas.height = canvas.clientHeight;
|
||||
|
||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
data: snapshotBlob,
|
||||
isError,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ["overviewSnapshot", cameraSide],
|
||||
queryFn: () => fetchSnapshot(cameraSide),
|
||||
refetchOnWindowFocus: false,
|
||||
refetchInterval: 1000,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!snapshotBlob) return;
|
||||
|
||||
const imgUrl = URL.createObjectURL(snapshotBlob);
|
||||
const img = new Image();
|
||||
imageRef.current = img;
|
||||
|
||||
img.onload = () => {
|
||||
drawImage();
|
||||
};
|
||||
img.src = imgUrl;
|
||||
|
||||
if (latestUrlRef.current) {
|
||||
URL.revokeObjectURL(latestUrlRef.current);
|
||||
}
|
||||
latestUrlRef.current = imgUrl;
|
||||
|
||||
return () => {
|
||||
if (latestUrlRef.current) {
|
||||
URL.revokeObjectURL(latestUrlRef.current);
|
||||
latestUrlRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [snapshotBlob, drawImage]);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("resize", drawImage);
|
||||
return () => {
|
||||
window.removeEventListener("resize", drawImage);
|
||||
};
|
||||
}, [drawImage]);
|
||||
|
||||
if (isError) {
|
||||
console.error("Snapshot error:", error);
|
||||
}
|
||||
|
||||
return { canvasRef };
|
||||
}
|
||||
Reference in New Issue
Block a user