问题描述
基本情景
我在客户端加载了几张图片。其中一些来自另一个域,有些则不是。有些我可以使用,有些则没有。
I'm loading several images on the client side. Some of them are from another domain, some are not. Some I may be able to access using the crossOrigin
attribute, some not.
基本要求是检索可能的图片。
The basic requirement is to retrieve a dataURL for the images where possible.
问题
将图像绘制到canvas元素后(我需要获取dataURL,对吗?),如何在没有<$ c $的情况下进行检查c>尝试...抓住阻止,画布是否已被污染?如果画布被污染了,我再也不能使用 toDataURL()
()。
After drawing the image to the canvas element (which I need to to to get a dataURL, right?), how can I check, without a try ... catch
block, whether the canvas has been tainted? If the canvas is tainted, I can't use toDataURL()
anymore (see MDN).
var image = new Image(),
canvas = document.createElement( 'canvas' ),
context = canvas.getContext( '2d' );
image.onload = function(){
// adjust dimensions of canvas
canvas.width = image.width;
canvas.height = image.height;
// insert image
context.drawImage( image, 0, 0 );
// how to check here?
// get dataurl
dataurl = tmpCanvas.toDataURL();
// do stuff with the dataurl
};
image.src = src; // some cross origin image
推荐答案
这是一个解决方案不会向本机对象添加属性:
Here is a solution that doesn't add properties to native objects:
function isTainted(ctx) {
try {
var pixel = ctx.getImageData(0, 0, 1, 1);
return false;
} catch(err) {
return (err.code === 18);
}
}
现在只需检查:
if (isTainted(ctx)) alert('Sorry, canvas is tainted!');
编辑:现在我看到你想要一个没有try-catch的解决方案。但是,这是检查的正确方法,因为没有向用户公开的原始清洁标志(仅供内部使用)。将属性添加到本机对象不建议。
NOW i see you wanted a solution without try-catch. Though, this is the proper way to check as there is no origin clean flag exposed to user (it's for internal use only). Adding properties to native object is not recommended.
这篇关于如果画布元素被污染了怎么检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!