I am using React, I have a canvas that is different size and shape depending on the screen size. If I want to draw something in the canvas I need to set dimensions for each individual screen size.
const [screenWidth, setScreenWidth] = useState(window.screen.width);
const screenFun = () => {
setScreenWidth(window.screen.width)
}
const playerFun = (screenWidth) => {
if(screenWidth >= 2100){
console.log('width bigger than 2100')
setPlayerWidth(18);
setPlayerHeight(12);
};
if(screenWidth >= 1850 && window.screen.width < 2100){
console.log('width bigger than 1850')
setPlayerWidth(30);
setPlayerHeight(20);
};
}
const Canvas = props => {
const canvasRef = useRef(null);
useEffect(() =>{
const canvas = canvasRef.current
const context = canvas.getContext('2d')
setCanvasWidth((canvas.width*(0.5))-10);
setCanvasHeight((canvas.height*(0.5))-15);
console.log('width: ' canvas.width ' height is: ' canvas.height)
context.fillStyle = '#00f4cc'
context.fillRect(canvasWidth, canvasHeight, playerWidth, playerHeight)
},[])
return <canvas ref={canvasRef} {...props}/>
}
useEffect(() =>{
screenFun();
})
useEffect(() =>{
playerFun();
},[screenWidth])
What I tried to do is update the state of the screenFun
variable everytime the screen is resized by having the useEffect(() =>{screenFun();})
function run forever in the background. I can't figure out how to get playerFun
to run whenever the screen is resized. Any help greatly appreciated!
CodePudding user response:
You'll want to use an event listener rather than useEffect
to update the screenWidth
variable. useEffect
is tied to the React component lifecycle and will only run when the component rerenders, which is not related to window resizing.
To use an event listener, you can do something like this:
React.useEffect(() => {
window.addEventListener("resize", screenFun);
return () => window.removeEventListener("resize", screenFun);
}, [screenFun]);
and then remove the useEffect
you currently have that just calls screenFun
.