Home > Back-end >  Why is the image not appearing on the canvas , Does it have to do with my useEffect ? (React.js)
Why is the image not appearing on the canvas , Does it have to do with my useEffect ? (React.js)

Time:09-07

This is my code :

const Testing = () => {
  
  const canvasRef = useRef(null)
  const imageRef = useRef(null)

  useEffect(() => {
    const image = imageRef.current
    const canvas = canvasRef.current
    canvas.width = 100
    canvas.height = 100

    const context = canvas.getContext('2d')
    context.drawImage(image , 0 , 0 , canvas.width , canvas.height)
    
    console.log(context.getImageData(0, 0, canvas.width , canvas.height)) 
  }, [])

  return (
    <>
      <img src={image} alt="" className={styles.theImage} ref={imageRef} />
      <canvas className={styles.canvasCont} ref={canvasRef}>

      </canvas>
    </>
  )
}

The canvas is empty however when I change anything in the dependency of the useEffect it works then when i refresh the page it goes back to not working again. Any idea what is causing that behavior ?

CodePudding user response:

You need to wait for the load event of the image before trying to copy it to the canvas.

Something like

const Testing = () => {
  const canvasRef = useRef(null);
  const imageRef = useRef(null);
  const [imageLoaded, setImageLoaded] = useState(false);

  const handleImageLoad = useCallback(() => {
    setImageLoaded(true);
  }, []);

  useEffect(() => {
    if (imageLoaded) {
      const image = imageRef.current;
      const canvas = canvasRef.current;
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");
      context.drawImage(image, 0, 0, canvas.width, canvas.height);

      console.log(context.getImageData(0, 0, canvas.width, canvas.height));
    }
  }, [imageLoaded]);
  
  return (
    <>
      <img src={image} alt="" className={styles.theImage} ref={imageRef} onl oad={handleImageLoad}/>
      <canvas className={styles.canvasCont} ref={canvasRef}></canvas>
    </>
  )
}

demo: https://codesandbox.io/s/dazzling-mendeleev-zv7uro?file=/src/App.js

  • Related