1

I would like to load an image into a <canvas> on my laptop so I can use getImageData(). I am using javascript in a local .html file. It is not a live, web facing project. Just a personal project.

I get the error: Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data. at Image.loadedImage when I try and do this.

What is the easiest solution to this problem? I think in the past I may have installed an Apache server just to address this issue! I just tried hfs but it did not work (to fix this issue).

Note that this cannot be fixed using img.crossOrigin = "Anonymous" or by running on Firefox as other, out of date, answers to related problems have suggested.

iPadDeveloper2011
  • 4,560
  • 1
  • 25
  • 36
  • 1
    adding `img.crossOrigin = "Anonymous"` to your image might help [see also](https://stackoverflow.com/questions/22097747/how-to-fix-getimagedata-error-the-canvas-has-been-tainted-by-cross-origin-data) – IT goldman Aug 07 '23 at 00:53
  • Without CORS, you cannot access the contents of images. This also applies when copying the image to a canvas (the canvas becomes tainted). `file:` urls always fail the CORS checks. – Ouroborus Aug 07 '23 at 01:14

1 Answers1

1

Currently, I've found that installing and running Rebex solves the problem (must transfer files to wwwroot)

iPadDeveloper2011
  • 4,560
  • 1
  • 25
  • 36
  • 1
    This is because Rebex is a web server and so you're no longer accessing the files via `file:` urls. Any web server would have worked. – Ouroborus Aug 07 '23 at 01:18
  • Probably the best way to do this would be to run the Rebex executable in the folder the original .html file was in. Then you just move everything into the wwwroot folder, in that folder. – iPadDeveloper2011 Aug 07 '23 at 01:18
  • @Ouroborus, yes, thanks, I think I get it. Pity that is the only way to do it. Rebex seems like a good solution as it is basically no setup required and very easy to manage. – iPadDeveloper2011 Aug 07 '23 at 01:20
  • @Ouroborus, curious that hfs didn't work then. Not sure why. – iPadDeveloper2011 Aug 07 '23 at 01:22
  • I suspect Rebex is HTTPS by default and HFS is HTTP by default. CORS generally needs HTTPS as a secure context. HTTP can work, but supports far less capability. For example, you may notice that a lot of the newer web APIs require HTTPS/CORS along with the correct permissions. – Ouroborus Aug 09 '23 at 20:18
  • @Ouroborus. I just checked how I am accessing and I'm using http://localhost... so its not that. No matter, I have a working solution. Thanks. – iPadDeveloper2011 Aug 16 '23 at 04:53