1.负面滤镜会从255中减去每个像素的红绿蓝分量值,再将差值设置回去。等同于翻转了该像素的颜色。
var imagedata = context.getImageData(0, 0, canvas.width, canvas.height),
data = imagedata.data;
for(i=0; i <= data.length - 4; i+=4) {
data[i] = 255 - data[i]
data[i+1] = 255 - data[i+1];
data[i+2] = 255 - data[i+2];
}
context.putImageData(imagedata, 0, 0);
2.黑白滤镜会计算出每个像素红绿蓝分量值的平均值,然后将三个分量都设置成这个平均值。
imagedata = context.getImageData(0, 0,
canvas.width, canvas.height);
data = imagedata.data;
for(i=0; i < data.length - 4; i+=4) {
average = (data[i] + data[i+1] + data[i+2]) / 3;
data[i] = average;
data[i+1] = average;
data[i+2] = average;
}
context.putImageData(imagedata, 0, 0);
3.浮雕滤镜使用“边缘测试”技术,需要计算当前像素值和其右方和下方像素值,同时要考虑要考虑边界条件。
imagedata = context.getImageData(0, 0,
canvas.width, canvas.height);
data = imagedata.data;
width = imagedata.width;
length = data.length;
for (i=0; i < length; i++) { // loop through every pixel
// if we won't overrun the bounds of the array
if (i <= length-width*4) {
// if it's not an alpha
if ((i+1) % 4 !== 0) {
// if it's the last pixel in the row, there is
// no pixel to the right, so copy previous pixel's
// values.
if ((i+4) % (width*4) == 0) {
data[i] = data[i-4];
data[i+1] = data[i-3];
data[i+2] = data[i-2];
data[i+3] = data[i-1];
i+=4;
}
else { // not the last pixel in the row
data[i] = 255/2 // Average value
+ 2*data[i] // current pixel
- data[i+4] // next pixel
- data[i+width*4]; // pixel underneath
}
}
}
else { // last row, no pixels underneath,
// so copy pixel above
if ((i+1) % 4 !== 0) {
data[i] = data[i-width*4];
}
}
}
context.putImageData(imagedata, 0, 0);
4.墨镜滤镜
for (i=0; i < length; ++i) {
if ((i+1) % 4 != 0) {
if ((i+4) % (width*4) == 0) { // last pixel in a row
data[i] = data[i-4];
data[i+1] = data[i-3];
data[i+2] = data[i-2];
data[i+3] = data[i-1];
i+=4;
}
else {
data[i] = 2*data[i] - data[i+4] - 0.5*data[i+4];
}
}
}