Javascript Canvas Get images pixel data

Deadly 提交于 2020-01-07 04:07:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17030889/javascript-canvas-get-images-pixel-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!