HTML5画布中的跨原始数据 [英] Cross-origin data in HTML5 canvas
问题描述
我在js中加载图像并将其绘制到画布上。绘制后,我从画布中检索imageData:
I'm loading an image in js and draw it into a canvas. After drawing, i retrieve imageData from the canvas:
var img = new Image();
img.onload = function() {
canvas.drawImage(img, 0, 0);
originalImageData = canvas.getImageData(0,0,width, height)); //chrome fails
}
img.src = 'picture.jpeg';
这在Safari和Firefox中都能正常工作,但在Chrome中失败,并显示以下消息:
This works perfectly both in Safari and Firefox, but fails in Chrome with the following message:
无法从画布中获取图片数据,因为画布已被跨原始数据污染。
Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
javascript文件和图片位于同一目录,所以我不明白chorme的行为。
The javascript file and the image are located in the same directory, so i don't understand the behavior of chorme.
推荐答案
要启用CORS(跨源资源共享 a>)为图片传递带有图片响应的HTTP标头:
To enable CORS (Cross-Origin Resource Sharing) for your images pass the HTTP header with the image response:
Access-Control-Allow-Origin: *
来源由网页的网域和通讯协定(例如http和https不相同)
The origin is determined by domain and protocol (e.g. http and https are not the same) of the webpage and not the location of the script.
如果您使用file://运行在本地,这通常被视为跨域问题;因此最好通过
If you are running locally using file:// this is generally always seen as a cross domain issue; so its better to go via
http://localhost/
这篇关于HTML5画布中的跨原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!