CanvasContext2D drawImage() issue [onload and CORS]
CanvasContext2D drawImage() issue [onload and CORS]
我试图在画布上绘制图像之前,我得到它的dataURL()
,但返回的数据就像空的。
当我在控制台中检查它时,我看到字符串中有很多A
:("data:image/png;base64,iVBO..some random chars... bQhfoAAAAAAAAAA... a lot of A ...AAAASUVORK5CYII="
)
当我尝试将画布附加到文档时,也没有绘制任何内容,并且在控制台中也没有抛出任何错误。
这里有什么问题?
下面是我的代码:var img = new Image();
img.src = "http://somerandomWebsite/picture.png";
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0); // this doesn't seem to work
var dataURL = canvas.toDataURL(); // this will give me a lot of "A"
doSomething(dataURL);
另外,在进行快速刷新时,图像被正确地绘制到画布上,但我在控制台上得到一个错误消息,dataURL
为空。
Firefox提示:"SecurityError: The operation is insecure."、
在Chrome浏览器中,它是"Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement:受污染的画布可能无法导出。"、
在IE上,我只是得到"SecurityError"。
您必须等待您的图像已加载,然后才能在画布上绘制它。
要做到这一点,只需使用<img>
元素的load
事件处理程序:
// create a new image
var img = new Image();
// declare a function to call once the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0);
var dataURL = canvas.toDataURL();
// now you can do something with the dataURL
doSomething(dataURL);
}
// now set the image's src
img.src = "http://somerandomWebsite/picture.png";
此外,为了使画布的context.toDataURL()
和context.getImageData
正常工作,您必须以跨原点兼容的方式获取图像资源,否则画布将被"污染",这意味着任何获取像素数据的方法都将被阻止。
- 如果您的图像来自同一个服务器,没有问题。
- 如果您的图像是从外部服务器提供的,请确保它允许您的图像在其跨域标头中,并将
img.crossOrigin
设置为"use-credentials"
。 - 如果服务器不允许匿名请求,可以将
img.crossOrigin
设置为"anonymous"
。
注意: CORS 头是由服务器发送的, cross-origin
属性只会让它知道你想使用CORS来获取图像数据,如果服务器设置不正确,你无法绕过它。还有一些用户代理(IE &Safari)还没有实现这个属性。
边缘情况:如果您的一些图像来自您的服务器,有些来自CORS兼容的服务器,那么您可能希望使用onerror
事件处理程序,如果您将cross-origin
属性设置为"anonymous"
,则应该在非CORS服务器上触发。
function corsError(){
this.crossOrigin='';
this.src='';
this.removeEventListener('error', corsError, false);
}
img.addEventListener('error', corsError, false);
- Selenium WebDriver and JavaScript change
- window.onload没有'无法在Android WebView中工作
- JavaScript-动态SVG-onload属性-未触发事件
- 在phonegap中为android调用onload函数的最佳方式
- PHP and Javascript functions
- Javascript Return and if/else
- image.onload事件和浏览器缓存
- 将函数从onclick修改为onload
- SetTimeout and clearTimeout in Javascript
- Combine onload, onresize and onclick
- Setting viewScope onLoad and onResize
- Mixing window.onload and jQuery $(function(){})
- JavaScript onload and DOM
- Javascript onload and onunload
- Javascript unonload and onload function
- window.onload and getelementbyid returns null
- CanvasContext2D drawImage() issue [onload and CORS]
- Dojo and the onload event
- JavaScript! window.onload = someFunction and window.onload =
- getElementById and onLoad