Canvas 的 context 调用 getImageData() 获取 canvas 中图片的像素数据,处理好后再调用 putImageData() 设置回 canvas。
1 2 3 4 5 6 7 8
| var canvas = $('#canvas').get(0); canvas.width = 500; canvas.height = 300; var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); grayscale(imageData); ctx.putImageData(imageData, 0, 0);
|
灰度效果
1 2 3 4 5 6 7 8 9 10 11
| function grayscale(pixels) { var d = pixels.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; } }
|
d 是一个像素颜色分量的整数数组,每 4 个值对应一个像素的 4 个颜色分量 rgba:
- d[i+0] 为红色值
- d[i+1] 为绿色值
- d[i+2] 为蓝色值
- d[i+3] 为 alpha 通道值
复古效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function siepa(pixels) { var d = pixels.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] = (r * 0.393) + (g * 0.769) + (b * 0.189); d[i + 1] = (r * 0.349) + (g * 0.686) + (b * 0.168); d[i + 2] = (r * 0.272) + (g * 0.534) + (b * 0.131); } }
|
红色蒙版
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
function red(pixels) { var d = pixels.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] = (r + g + b) / 3; d[i + 1] = d[i + 2] = 0; } }
|
亮度效果
1 2 3 4 5 6 7 8 9 10
| function brightness(pixels, delta) { var d = pixels.data;
for (var i = 0; i < d.length; i += 4) { d[i] += delta; d[i + 1] += delta; d[i + 2] += delta; } }
|
反转效果
1 2 3 4 5 6 7 8 9 10
| function invert(pixels, delta) { var d = pixels.data;
for (var i = 0; i < d.length; i += 4) { d[i] = 255 - d[i]; d[i + 1] = 255 - d[i + 1]; d[i + 2] = 255 - d[i + 2]; } }
|