CanvasContext2D drawImage()问题[onload和CORS] [英] CanvasContext2D drawImage() issue [onload and CORS]

查看:508
本文介绍了CanvasContext2D drawImage()问题[onload和CORS]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在画布上绘制一个图像,然后得到它的 dataURL(),但返回的数据是空的。

I am trying to paint an image on a canvas before I get its dataURL(), but the data returned is like empty.

当我在控制台中检查时,我看到字符串中有很多 A code>data:image / png; base64,iVBO..some随机字符... bQhfoAAAAAAAAAA ...很多A ... AAAASUVORK5CYII =)

When I check it in the console, I see there is a lot of A in the string : ("data:image/png;base64,iVBO..some random chars... bQhfoAAAAAAAAAA... a lot of A ...AAAASUVORK5CYII=")

当我尝试将canvas附加到文档时,没有绘制任何东西,我没有在控制台中抛出任何错误。

When I try to append the canvas to the document, nothing is drawn either and I don't have any error thrown in the console.

这里有什么问题?

这里是我的代码:

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 为空。

Also, when doing a quick refresh, the image gets drawn correctly onto the canvas but I've got an error message in the console and dataURL is empty.

Firefox中的邮件是:SecurityError:操作不安全。

在Chrome中, em>未捕获安全错误:无法在'HTMLCanvasElement'上执行'toDataURL':可能无法导出已污染的画布,

和在IE上我只是得到了SecurityError。

The message in Firefox is : "SecurityError: The operation is insecure.",
in Chrome it is "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.",
and on IE I just get "SecurityError".

这是什么意思?

推荐答案

您的图片已加载 ,然后才能在画布上绘制。

You have to wait that your image has loaded before you can paint it on the canvas.

只需使用< img>的 load 元素:

To do so, simply use the load event handler of your <img> element :

// 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 才能正常工作,你必须在跨源符合方式,否则画布会被污染,这意味着任何获取像素数据的方法都会被阻止。

Also, for the canvas' context.toDataURL() and context.getImageData to work properly, you have to get your image resource in a cross-origin compliant way, otherwise the canvas is "tainted" which means that any method to get pixels data will be blocked.


  • 如果您的图片来自相同的服务器,则没有问题。

  • 如果您的图片是从外部伺服器放送,请确定您的图片允许在其跨来源标头中,并设定 img .crossOrigin use-credentials

  • 如果服务器允许匿名请求,您可以将 img.crossOrigin 设置为anonymous

  • If your image comes from the same server, no problem.
  • If your image is served from an external server, be sure that it allows yours in its cross-origin headers and set the img.crossOrigin to "use-credentials".
  • If the server does allow anonymous requests, you can set the img.crossOrigin to "anonymous".

=https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS =nofollow> CORS 标头由服务器发送跨源的属性只会让它知道你想使用CORS获取图像数据,如果服务器未正确设置。

也有一些UserAgent(IE& Safari)仍未实现此属性。

Nota Bene : CORS header is sent by the server, the cross-origin attribute will only let it know that you want to use CORS to get the image data, in no way you can circumvent it if the server is not set properly.
Also some UserAgents (IE & Safari) still haven't implemented this attribute.

:如果您的某些图片来自您的服务器,并且有些图片来自CORS兼容的图片,那么您可能需要使用 onerror 事件处理程序您在非CORS服务器上将跨源属性设置为anonymous

Edge Case : If some of your images are from your server and some are from a CORS compliant one, then you may want to use the onerror event handler which should fire if you set the cross-origin attribute to "anonymous" on a non CORS server.

function corsError(){
  this.crossOrigin='';
  this.src='';
  this.removeEventListener('error', corsError, false);
} 
img.addEventListener('error', corsError, false);

这篇关于CanvasContext2D drawImage()问题[onload和CORS]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆