Skip to content

canvas绘制高斯模糊 #78

@et-hh

Description

@et-hh

高斯模糊的算法 - 阮一峰

const gaussBlur = function (imgData, radius) {
 
      radius *= 3;    //不知为什么,我的模糊半径是 css中 filter:bulr 值的三倍时效果才一致。

      //Copy图片内容
      let pixes = new Uint8ClampedArray(imgData.data);
      const width = imgData.width;
      const height = imgData.height;
      let gaussMatrix = [],
          gaussSum,
          x, y,
          r, g, b, a,
          i, j, k,
          w;

      radius = Math.floor(radius);
      const sigma = radius / 3;

      a = 1 / (Math.sqrt(2 * Math.PI) * sigma);
      b = -1 / (2 * sigma * sigma);

      //生成高斯矩阵
      for (i = -radius; i <= radius; i++) {
          gaussMatrix.push(a * Math.exp(b * i * i));
      }

      //y 方向一维高斯运算
      for (x = 0; x < width; x++) {
          for (y = 0; y < height; y++) {
              r = g = b = a = gaussSum = 0;
              for (j = -radius; j <= radius; j++) {
                  k = y + j;

                  if (k >= 0 && k < height) {
                      i = (k * width + x) * 4;
                      w = gaussMatrix[j + radius];

                      r += pixes[i] * w;
                      g += pixes[i + 1] * w;
                      b += pixes[i + 2] * w;
                      a += pixes[i + 3] * w;

                      gaussSum += w;
                  }
              }
              i = (y * width + x) * 4;
              imgData.data.set([r, g, b, a].map(v=>v / gaussSum), i);
          }
      }

      return imgData
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions