I think I may be misusing useRef
here. When I try to draw to the canvas I am getting the following error: cannot set 'fillStyle' of undefined
.
import React, { useEffect, useRef } from "react";
import useWindowSize from "../hooks/useWindowSize";
export default function Player() {
const canvasRef = useRef();
const ctx = useRef();
useEffect(() => {
ctx.current = canvasRef.current.getContext("2d");
}, []);
ctx.current.fillStyle = "green";
ctx.current.fillRect(20, 20, 150, 100);
return (
<React.Fragment>
<div>Hello</div>
<canvas ref={canvasRef} width="500" height="500" />
</React.Fragment>
);
}
The first time you are trying to access ctx.current
, it's still undefined because the assignment inside this effect still didn't happen:
useEffect(()=>{
ctx.current = canvasRef.current.getContext('2d')
},[])
This is because the effect is run after the rendering phase.
You need to do that inside useEffect
instead:
useEffect(()=>{
ctx.current = canvasRef.current.getContext('2d')
ctx.current.fillStyle= "green"
ctx.current.fillRect(20,20,150,100)
},[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With