CanvasContext2D drawImage() issue [onload and CORS]

CanvasContext2D drawImage() issue [onload and CORS]

本文关键字:onload and CORS issue drawImage CanvasContext2D      更新时间:2023-09-26

我试图在画布上绘制图像之前,我得到它的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);