| import { useState, useEffect, useCallback, useRef } from 'react'; |
|
|
| |
| |
| |
| |
| const useDeviceAndCanvas = () => { |
| |
| const [isMobile, setIsMobile] = useState(false); |
| const [isMac, setIsMac] = useState(false); |
| |
| |
| const [canvasWidth, setCanvasWidth] = useState(640); |
| const [canvasHeight, setCanvasHeight] = useState(480); |
| const [videoAspectRatio, setVideoAspectRatio] = useState(4/3); |
| const isComponentMounted = useRef(true); |
| |
| |
| useEffect(() => { |
| isComponentMounted.current = true; |
| |
| const checkMobile = () => { |
| const mobile = window.innerWidth < 768; |
| setIsMobile(mobile); |
| }; |
| |
| checkMobile(); |
| window.addEventListener('resize', checkMobile); |
| |
| |
| if (typeof navigator !== 'undefined') { |
| setIsMac(navigator.platform.includes('Mac')); |
| } |
| |
| return () => { |
| isComponentMounted.current = false; |
| window.removeEventListener('resize', checkMobile); |
| }; |
| }, []); |
| |
| |
| const updateCanvasSize = useCallback((aspectRatio) => { |
| if (!isComponentMounted.current) return; |
| |
| const containerWidth = document.querySelector('.canvas-container')?.clientWidth || window.innerWidth; |
| const windowHeight = window.innerHeight; |
| |
| |
| const maxWidth = Math.min(containerWidth, isMobile ? 640 : 960); |
| |
| const maxHeight = isMobile ? windowHeight * 0.7 : windowHeight * 0.8; |
| |
| |
| let width = maxWidth; |
| let height = width / aspectRatio; |
| |
| |
| if (height > maxHeight) { |
| height = maxHeight; |
| width = height * aspectRatio; |
| } |
| |
| |
| if (width > containerWidth) { |
| width = containerWidth; |
| height = width / aspectRatio; |
| } |
| |
| |
| setCanvasWidth(Math.round(width)); |
| setCanvasHeight(Math.round(height)); |
| }, [isMobile]); |
| |
| return { |
| |
| isMobile, |
| isMac, |
| |
| |
| canvasWidth, |
| canvasHeight, |
| videoAspectRatio, |
| setVideoAspectRatio, |
| updateCanvasSize, |
| isComponentMounted |
| }; |
| }; |
|
|
| export default useDeviceAndCanvas; |