Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...