美文网首页
canvas彩色图片处理为黑白

canvas彩色图片处理为黑白

作者: 未來Miral | 来源:发表于2018-11-09 10:42 被阅读0次
    const warp = document.getElementById('mainPic');
      // 初始化主canvas
      const obj = document.getElementById('canvas');
      const ctx = obj.getContext('2d');
    
      // 原始图片
      const pic = new Image();
      pic.src = "pic.jpg";
      
      // 加载图片
      pic.onload = function () {
        ctx.drawImage(this, 0, 0, this.width, this.height);
    
        // 获取图片像素信息
        let imageData = ctx.getImageData(0,0,obj.width,obj.height);
        let pixels = imageData.data;
        
        //遍历像素点
        for (let i=0; i<pixels.length; i+=4){
          let r = pixels[i];
          let g = pixels[i+1];
          let b = pixels[i+2];
          
          originImageData[i] = r;
          originImageData[i+1] = g;
          originImageData[i+2] = b;
    
          //获取灰色
          let gray = parseInt((r+g+b)/3);
    
          pixels[i] = gray;
          pixels[i+1] = gray;
          pixels[i+2] = gray;
        }
    
        ctx.putImageData(imageData, 0,0);
    
        // 点击事件
        obj.addEventListener('click', function(event) {
          let rect = obj.getBoundingClientRect();
          let cx = event.clientX - rect.left * (obj.width / rect.width);
          let cy = event.clientY - rect.top * (obj.height / rect.height);
          console.log(cx,cy);
        });
      }
    

    相关文章

      网友评论

          本文标题:canvas彩色图片处理为黑白

          本文链接:https://www.haomeiwen.com/subject/wvmnxqtx.html