简体   繁体   中英

Javascript Canvas Get images pixel data

I have a two part question about javascript canvas:

Part 1:
I have a .jpg in the same file as my html document. I was wondering if there was a simple way of getting a pixel's color in that file without having to use context.getImageData().

Part 2: (If part 1 is too complex to be useful.)
If I directly copy the code from this site: W3 schools getImageData() into an html file on my desktop, and add an image named img_the_scream.jpg to my desktop, then run it I get this error:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data. test.html:15
Uncaught Error: SecurityError: DOM Exception 18 

I don't really know why it works for the site but not for me.

That's a limit imposed by the Same Origin Policy : you can't read in JavaScript data served by another origin apart if the server explicitly allows it using CORS headers .

If you want to get the pixels of an image served by another server than yours and this server doesn't set this header, then you'll have to work on your server, either by using a kind of proxy or by fetching the image server side.

Note that browsers consider all files coming from file:// to be of different origin. If you try to do it locally, you must use an http server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM