📜  画布中的灰度图像 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:14.908000             🧑  作者: Mango

代码示例1
window.onload = function() {
let canvas = document.getElementById("c");

      let ctx = canvas.getContext("2d");
    canvas.width=50;
    canvas.height=50;

        let srcImg = document.getElementById("sof");
        ctx.drawImage(srcImg, 0, 0, ctx.canvas.width, ctx.canvas.height);
        let imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
        let pixels = imgData.data;
        for (var i = 0; i < pixels.length; i += 4) {
          
        let lightness = parseInt((pixels[i] + pixels[i + 1] + pixels[i + 2])/3);
    
          pixels[i] = lightness; 
          pixels[i + 1] = lightness; 
          pixels[i + 2] = lightness; 
        }
        ctx.putImageData(imgData, 0, 0);
      }