I have the following code where the contextRef is not null as expected:
useEffect(() => {
contextRef.current = canvasRef.current.getContext("2d")
console.log("In useEffect, contextRef=", contextRef)
}, [])
const onCanvasClicked = () => {
console.log("DEBUG---- contextRef:", contextRef)
contextRef.current.drawImage(image, 20, 20)
}
while if add a setImage inside the useEffect
then the contextRef
printed by the onCanvasClicked
becomes null
, why?
useEffect(() => {
contextRef.current = canvasRef.current.getContext("2d")
console.log("In useEffect, contextRef=", contextRef)
const myImage = new Image(200,200)
myImage.src = "https://s-media-cache-ak0.pinimg.com/236x/d7/b3/cf/d7b3cfe04c2dc44400547ea6ef94ba35.jpg"
setImage(myImage) // <------------------ the cause
}, [])
const onCanvasClicked = () => {
console.log("DEBUG---- contextRef:", contextRef) // <----------- becomes null
contextRef.current.drawImage(image, 20, 20)
}
import {createRef, useEffect, useState} from "react";
const ImageDisplay = () => {
const [image, setImage] = useState()
const canvasRef = createRef()
const contextRef = createRef()
useEffect(() => {
contextRef.current = canvasRef.current.getContext("2d")
console.log("In useEffect, contextRef=", contextRef)
const myImage = new Image(200,200)
myImage.src = "https://s-media-cache-ak0.pinimg.com/236x/d7/b3/cf/d7b3cfe04c2dc44400547ea6ef94ba35.jpg"
setImage(myImage)
}, [])
const onCanvasClicked = () => {
contextRef.current.drawImage(image, 20, 20)
}
return <div>
<canvas
ref={canvasRef}
width={640}
height={425}
onClick={onCanvasClicked}
/>
</div>
}
export default ImageDisplay