Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D':
The canvas has been tainted by cross-origin data
我只在chrome中遇到错误。我的代码(以下)在mozilla中运行良好。我没有corss域名问题。那么为什么我会在chrome中遇到错误?
var wheel_canvas, wheel_context, can_w, can_h, wheel_grd;
var LARGE_RADIUS = 160;
var SMALL_RADIUS = 120;
var wheel_canvas = document.getElementById('wheel_canvas');
var wheel_context = wheel_canvas.getContext('2d');
var can_w = $(wheel_canvas).width();
var can_h = $(wheel_canvas).height();
var centerX = can_w / 2, centerY = can_h / 2;
var wheel_grd = null;
test('#FF0000');
function test(hex)
{
$('#clrpicker').css({'left': 210, 'top': 210 });
inverted = hexBW(hex);
$('#color_val_show').val(hex);
current_color_hex_val_selected = hex;
$('#color_val_show').css({'color':inverted,'background':hex});
fillGradientCirle(hex);
}
function fillGradientCirle(hex)
{
wheel_context.rect(0, 0, can_w, can_h);
wheel_grd = wheel_context.createLinearGradient(1, 1, 0, can_w, can_h);
wheel_grd.addColorStop(1, '#ffffff');
wheel_grd.addColorStop(0.5, hex);
wheel_grd.addColorStop(0, '#000000');
wheel_context.fillStyle = wheel_grd;
wheel_context.beginPath();
wheel_context.arc(centerX, centerY, LARGE_RADIUS, 0, 2 * Math.PI);
wheel_context.fill();
}
$(wheel_canvas).click(function (e)
{
$.event.fix(e);
x = e.pageX;
y = e.pageY;
can_p = $(this).offset();
x = x - $(document).scrollLeft() - can_p.left;
// Fixed typo
y = y - $(document).scrollTop() - can_p.top;
if (Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY)) < SMALL_RADIUS) return; // Precaution
$('#wheel_picker').css({ 'left': x-8 + 'px', 'top': y-8 + 'px' });
var data = wheel_context.getImageData(x, y, 1, 1).data;
pixelData = data;
rgbString = 'rgb(' + pixelData[0] + ', ' + pixelData[1] + ', ' + pixelData[2] + ')';
hex = rgb2hex(rgbString);
inverted = hexBW(hex);
$('#color_val_show').val(hex);
current_color_hex_val_selected = hex;
$('#color_val_show').css({'color':inverted,'background':hex});
$('#feedback').html("Coordinates : " + x + "," + y + " Color: " + hex);
});
答案 0 :(得分:2)
如果这是所有代码并且您不使用任何跨源图像,那么唯一突出的错误就是这一行:
wheel_grd = wheel_context.createLinearGradient(1, 1, 0, can_w, can_h);
这应该只有four arguments而不是五。最后一个论点可能会以某种方式绊倒Chrome。
尝试将其更改为:
// x0 y0 x1 y1
wheel_grd = wheel_context.createLinearGradient(1, 0, can_w, can_h);
您可以考虑查看的其他错误:
要阅读画布的正确尺寸(除非您打算因某种原因阅读CSS尺寸),您需要使用以下内容:
var can_w = wheel_canvas.width; //$(wheel_canvas).width();
var can_h = wheel_canvas.height; //$(wheel_canvas).height();
或者如果你坚持使用jQuery:
var can_w = $(wheel_canvas).prop('width');
var can_h = $(wheel_canvas).prop('height');
希望这有帮助!
答案 1 :(得分:1)
对于测试,您还可以使用--allow-file-access-from-files
作为Chrome的命令行参数;这将允许您使用本地文件。