天天看点

html5 Canvas 图片灰度处理

图片灰度处理有什么用?

实现思路

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas-getImageData灰度处理</title>
  <style>
   .square{
    width:20px;
    height:20px;
    display:block;
    background-color:gray;
   }
   .canvas{
    margin:10 auto;
   }
   .show{
    margin:0 auto;
    width:300px;
   }

  </style>
</head>
<body>
 <canvas class='canvas' id="myCanvas"></canvas>
 <div class='show'>
  <input id='gray' type='button' value='灰度' />
 </div>

<script type="text/javascript">
 var canvas = document.getElementById('myCanvas');
 var ctx = canvas.getContext('2d');

let monkeyKing = new Image();
monkeyKing.src='monkeyKing.png';
//console.dir(monkeyKing);
// 图片加载成功后再绘制 否则drawImage会失败
monkeyKing.onload=function(){
 canvas.width = monkeyKing.width;
 canvas.height=monkeyKing.height;
   ctx.drawImage(monkeyKing,0,0,monkeyKing.width,monkeyKing.height);
}
// 灰度处理
function gray(){
  console.log('gray');
  let imageData = ctx.getImageData(0,0,monkeyKing.width,monkeyKing.height);
  let pxArr = imageData.data;
  // 一个像素对应数组中的四个值,分别表示 r g b a
  let len = pxArr.length/4;
  for(let i=0;i<len;i++){
    let indexR = i*4+0;
    let indexG = i*4+1;
    let indexB = i*4+2;
    let gray = parseInt((pxArr[indexR]+pxArr[indexG]+pxArr[indexB])/3);
    pxArr[indexR]=pxArr[indexG]=pxArr[indexB]=gray;
  }
  //console.log(pxArr);
  imageData.data = pxArr;
  ctx.putImageData(imageData,0,0);
}
document.getElementById('gray').onclick=gray;
</script>
</body>  
</html>