Search code examples
reactjscanvas

How to fix "Access to image [Image Url] from origin http:localhost:3000 has been blocked by CORS Policy (React & HTML Canvas)


I have a code that takes a image url and draws it on the canvas however i get faced with this error and my image does not appear on the canvas , the canvas stays empty.

ERROR

Access to image at 'https://storage.googleapis.com/object-cut-images/54062ac7-59dd-4684-baf4-840e6c5a2c3c.png' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Below IS My Code for drawing the image on the canvas

const Testing = () => {

  const canvasRef = useRef(null)
  

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

    const context = canvas.getContext('2d')
    const image = new Image()
    image.src= "https://storage.googleapis.com/object-cut-images/54062ac7-59dd-4684-baf4-840e6c5a2c3c.png"
    image.crossOrigin = "Anonymous";
    image.onload = () => {
      context.drawImage(image , 0 , 0 , canvas.width , canvas.height)
      console.log(context.getImageData(0, 0, canvas.width , canvas.height).data.length)
    }
     
  }, [])

  return (
    <>
      <canvas className={styles.canvasCont} ref={canvasRef}>

      </canvas>
    </>
  )
}

As can be seen in the code I have even added "image.crossOrigin" to be anonymous so why is it not functioning properly? Am I missing something?


Solution

  • I was able to find the solution to this by simply setting up a proxy in my package.JSON file like so:

    "proxy": "http://localhost:3000"
    

    And removed the "image.crossOrigin" and it works perfectly now!

    According to the error, it said "origin 'http://localhost:3000'" and that is why you see the proxy is "http://localhost:3000".