Is there a quick test to determine if a browser supports CORS-enabled images not tainting a canvas when drawn on them. I know Chrome 15 supports this, Firefox 9Beta but not Firefox 8, Safari doesn't, IE9 doesn't. But there must be a pretty simple test to determine this, is basically drawing on a canvas with an image and seeing if you get an exception when you try to get image data, or is there any other easy way to determine this.
Is there a quick test to determine if a browser supports CORS-enabled images not tainting a canvas when drawn on them. I know Chrome 15 supports this, Firefox 9Beta but not Firefox 8, Safari doesn't, IE9 doesn't. But there must be a pretty simple test to determine this, is basically drawing on a canvas with an image and seeing if you get an exception when you try to get image data, or is there any other easy way to determine this.
Share Improve this question asked Dec 8, 2011 at 23:02 Kris EricksonKris Erickson 33.8k26 gold badges121 silver badges179 bronze badges 1- 1 The method you described is probably easiest. – Michael Mior Commented Dec 8, 2011 at 23:05
3 Answers
Reset to default 8This seems to work:
if ('crossOrigin' in new Image())
// ...
Here is how I tested for CORS tained canvas support. If someone has a way without having to load an image, please post it here:
function CanvasFunctions() {
var _initialized = false, _corsNotSupported = false;
function DrawImage(image, src) {
jQuery.when(initialized()).then(function () {
if (_corsNotSupported) {
image.src = GetProxyImage(src);
} else {
image.src = src;
}
}
}
function initialized() {
if (_initialized) {
return true;
}
var dfd = $.Deferred();
var src = 'http://example./corsImage.jpg',
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
var ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, 200, 200);
try {
var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1;
console.log('Canvas was not tainted by CORS image, hit: ' + hit);
} catch (e) {
console.log('Canvas was tainted by CORS image, reverting to passthru for images');
_corsNotSupported = true;
}
_initialized = true;
dfd.resolve(true);
});
image.src = src;
return dfd.promise();
}
}
The simplest way to determine if a browser supports CORS is to look for the XHR's withCredentials property. IE uses the XDomainRequest object instead of XHR, so you need to look for that as well:
function supportsCors() {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Supports CORS
return true;
} else if (typeof XDomainRequest != "undefined") {
// IE
return true;
}
return false;
}