1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset='utf-8' /> 5 <style> 6 #canvas { 7 border: 1px dashed #aaa; 8 } 9 </style> 10 <script> 11 window.onload = function () { 12 var oCanvas = document.querySelector("#canvas"), 13 oGc = oCanvas.getContext('2d'); oImg = new Image(); 16 oImg.src = './img/mv.jpg'; 17 oImg.onload = function () { 18 oGc.drawImage(oImg, 10, 10); 19 var imgData = oGc.getImageData(10, 10, 200, 200), 20 data = imgData.data, avg = 0; 21 for( var i = 0; i < data.length; i += 4 ) { 22 avg = data[i] * 0.3 + data[i+1] * 0.3 + data[i+2] * 0.4; 23 data[i] = avg; 24 data[i+1] = avg; 25 data[i+2] = avg; 26 } oGc.putImageData( imgData, 220, 10 ); 29 } 30 } 31 </script> 32 </head> 33 <body> 34 <canvas></canvas> 35 </body> 36 </html>
三、调节亮度的强弱
在r、g、b、通道上加上一正值就是变亮,加上负值就是变暗
1 var oImg = new Image(); 2 oImg.src = './img/mv.jpg'; 3 oImg.onload = function () { 4 oGc.drawImage(oImg, 10, 10); 5 var imgData = oGc.getImageData(10, 10, 200, 200), 6 data = imgData.data, avg = 0; 7 for( var i = 0; i < data.length; i += 4 ) { 8 data[i] += 30; 9 data[i+1] += 50; 10 data[i+2] += 50; 11 } oGc.putImageData( imgData, 220, 10 ); 14 }
变暗:
data[i] -= 30;
data[i+1] -= 50;
data[i+2] -= 50;
四、复古效果
将r, g, b按比例混合相加。
1 var oImg = new Image(); 2 oImg.src = './img/mv.jpg'; 3 oImg.onload = function () { 4 oGc.drawImage(oImg, 10, 10); 5 var imgData = oGc.getImageData(10, 10, 200, 200), 6 data = imgData.data, avg = 0; 7 for( var i = 0; i < data.length; i += 4 ) { 8 r = data[i]; 9 g = data[i+1]; 10 b = data[i+2]; 11 data[i] = r * 0.3 + g * 0.4 + b * 0.3; 12 data[i+1] = r * 0.2 + g * 0.6 + b * 0.2; 13 data[i+2] = r * 0.4 + g * 0.3 + b * 0.3; 14 } oGc.putImageData( imgData, 220, 10 ); 17 }
五、蓝色蒙版
蓝色 蒙版就是让图片偏蓝色,将蓝色通道赋值为 r, g, b三原色的平均值,把绿色,红色通道设置为0,其他蒙版效果,只要设置对应的通道平均值,关闭其他通道即可.