Reputation: 63
Currently im trying to load a image into my canvas. The problem is, if im loading the page there is no image, but the image src logs correct in the console. If im saving my code, so react is doing a refresh i can see my canvas. Seems like there is something wrong with my useEffect?
//My Canvas:
const canvasRef = useRef(null);
//In my return() section
<canvas id="canvas" ref={canvasRef}> </canvas>
useEffect(() => {
fetch(`${process.env.REACT_APP_API_URL}/image/label`)
.then(async (x) => {
let resp = await x.json()
if(resp !== undefined && resp.id === undefined && resp.data === undefined) {
setNoImageAvailable(true)
}
//setImage(resp.data)
setId(resp.id);
currentImage.id = resp.id
const canvas = canvasRef.current as HTMLCanvasElement | null;
const context = canvas?.getContext('2d');
let bed = new Image();
bed.src = "https://images.unsplash.com/photo-1615874959474-d609969a20ed?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=580&q=80";
bed.onload = () => {
console.log(bed)
context?.drawImage(bed, 0, 0);
};
})
}, [reRenderValue])
Upvotes: 1
Views: 38
Reputation: 63
Wow, after a another few minutes i fixed it. The problem was like i excepted the useEffect. I made a new canvas drawing function and linked it to useEffect at the end like this:
const [canvas, setCanvas] = useState(false)
useEffect(() => {
fetch(`${process.env.REACT_APP_API_URL}/image/label`)
.then(async (x) => {
let resp = await x.json()
if(resp !== undefined && resp.id === undefined && resp.data === undefined) {
setNoImageAvailable(true)
}
setImage(resp.data)
setId(resp.id);
currentImage.id = resp.id
const canvas = canvasRef.current as HTMLCanvasElement | null;
const context = canvas?.getContext('2d')
draw(context)
})
}, [reRenderValue,canvas])
In draw you can do whatever you want with your canvas and you neet so setCanvas(true) so useEffect is not loading your canvas over and over again
Upvotes: 1