我想为 HTML5 画布实现一个简单的灰度过滤器,但我无法将图像数据作为像素抓取。我收到来自 FF 和 Chrome 的安全警告。最后,过滤器不会使图像变灰。
js:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function () {
if (image.width != canvas.width)
canvas.width = image.width;
if (image.height != canvas.height)
canvas.height = image.height;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, canvas.width, canvas.height);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
filter(imageData);
context.putImageData(imageData, 0, 0);
}
image.src = "http://i0.gmx.net/images/302/17520302,pd=2,h=192,mxh=600,mxw=800,w=300.jpg";
function filter(imageData){
var d = imageData.data;
for (var i = 0; i < d.length; i += 4) {
var r = d[i];
var g = d[i + 1];
var b = d[i + 2];
d[i] = d[i + 1] = d[i + 2] = (r+g+b)/3;
}
return imageData;
}