0

My question might be stupid, but I'm stuck with a simple task.

I'm writing a web browser game where I load images from a local folder to a 2d canvas, then, at some time, redraw it with getImageData(). The code sample is the following

let img = new Image()
// img.crossOrigin = "anonymous"
img.src = "assets/hidden.png"

let ctx = document.getElementById("canvas").getContext("2d")

img.onload = () => {
    console.log("loaded img", img.src)
    ctx.drawImage(img, 0, 0)

    let c = ctx.getImageData(0, 0, 10, 10)
}

The original problem was that calling getImageData() causes Uncaught DOMException: The operation is insecure. So I added img.crossOrigin = "anonymous" (context.getImageData() operation is insecure) to overcome this, but now the image is not loaded at all. How do I normally use images in canvas?

mishadr
  • 375
  • 1
  • 4
  • 9
  • Are you running a server or just opening the HTML file? When the image is not loaded at all, is there anything in the console? Does `onload` run? I don't know if it matters, but I usually set the `.src` property last, after `onload` and other properties have been set. – ggorlen Dec 31 '22 at 17:59
  • @ggorlen it is a static html page with this script and the assets folder located at the same place. Image is just not loading, nothing in the console. If I set `crossOrigin = "anonymous"` after loading, I get the previous security error – mishadr Dec 31 '22 at 18:01
  • 1
    OK, I'd try running a server: `python -m http.server` and navigate to `localhost:8000` in your browser. – ggorlen Dec 31 '22 at 18:01
  • well, when a server is run, it works.. thanks for help! But would it work if I publish my game at a web-page? – mishadr Dec 31 '22 at 18:07
  • It should, assuming the images are on the same domain. It was probably a CORS issue. – ggorlen Dec 31 '22 at 18:13
  • Canonical for running a local server [How to run html file on localhost?](https://stackoverflow.com/questions/38497334/how-to-run-html-file-on-localhost) – ggorlen Dec 31 '22 at 18:19

0 Answers0