我们可以通过下面几种方法,将其转换为灰度:
1.浮点算法:Gray=R*0.3+G*0.59+B*0.11
2.整数方法:Gray=(R*30+G*59+B*11)/100
3.移位方法:Gray =(R*76+G*151+B*28)>>8;
4.平均值法:Gray=(R+G+B)/3;
5.仅取绿色:Gray=G;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>gray</title> </head> <body> <canvas id='myCanvas' width='800' height='600'> your browser does not support canvas </canvas> <script type="text/javascript"> var c = document.getElementById('myCanvas'); var ctx = c.getContext('2d'); var img = new Image(); img.src = 'face.jpg'; img.onload = function() { ctx.drawImage(img, 0, 0); var imgData = ctx.getImageData(0, 0, 250, 250); var pixels = imgData.data; for (var i = 0, n = pixels.length; i < n; i += 4) { var grayscale = pixels[i] * .3 + pixels[i + 1] * .59 + pixels[i + 2] * .11; pixels[i] = grayscale; pixels[i + 1] = grayscale; pixels[i + 2] = grayscale; } ctx.putImageData(imgData, 250, 0); }; </script> </body> </html>