js改变图片颜色

   /**
       * 根据主题颜色修改图片颜色
       * @param  {[type]}   imgUrl    图片url
       * @param  {[type]}  color 主题颜色
       * @param  {Function} callback  返回值 返回base64
       */
      changeImageColor = (imgUrl, color = "#00ff7f", callback) => {
        let threshold = 114; //默认颜色阀值 为 114 ->和默认图相关
        let img = new Image();
        img.src = imgUrl;
        let newR = parseInt("0x" + color.substr(1, 2));
        let newG = parseInt("0x" + color.substr(3, 2));
        let newB = parseInt("0x" + color.substr(5, 2));
        //图片加载后进行处理
        img.onload = function () {
          console.log("wojinlaile");
          let width = img.width, height = img.height,canvas = document.createElement("canvas"),ctx = canvas.getContext("2d");
          canvas.width = width;
          canvas.height = height;
          // 将源图片复制到画布上
          ctx.drawImage(img, 0, 0, width, height);
          // 获取画布的像素信息
          let imageData = ctx.getImageData(0, 0, width, height),data = imageData.data;
          // 对像素集合中的单个像素进行循环,每个像素是由4个通道组成,所以要注意
          let i = 0;
          while (i < data.length) {
            let r = data[i++],
                g = data[i++],
                b = data[i++],
                a = data[i++];
            //计算透明度
            let alp = (255 - r) / (255 - threshold);
            //判断是否透明
            let isTransparent = r == 255 && g == 255 && b == 255 && a == 255;
            if (isTransparent) {
              data[i - 1] = 0;
            } else {
              data[i - 4] = newR;
              data[i - 3] = newG;
              data[i - 2] = newB;
              data[i - 1] = a !== 255 ? 255 - a : alp * 255; //处理透明的图片和不透明的图片
            }
          }
          // 将修改后的代码复制回画布中
          ctx.putImageData(imageData, 0, 0);
          // 图片导出为 png 格式
          let imgType = "png";
          let imgData = canvas.toDataURL(imgType);
          // console.log(imgData); // 生成base64
          callback && callback(imgData);
        };
        return img;
      },
        //使用方式 其中 data、style 为通过api读取的值
        this.changeImageColor("./img/2.png", "#f51ca6", (imgData) => {
          console.log(imgData);
        });
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值