如何应用锐度滤镜?

时间:2019-10-15 14:54:17

标签: angular canvas

我正在开发在Angular中应用过滤器的工具。我正在使用Canvas HTML组件来应用不同的过滤器。我没有遇到对比度或亮度问题,因为属性FILTER具有这种滤镜。

但是,我不能直接使用“清晰度”滤镜。我知道我必须对一些内核使用卷积,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

在现代浏览器中,您可以在画布上使用SVG过滤器,feConvolveMatrix可以使SVG过滤器变得简单明了:

const canvas = document.getElementById( 'canvas' );
const ctx = canvas.getContext( '2d' );
const matrix = document.getElementById( 'conv-matrix' );
let speed = 0.05;
let pow = 0;
const img = new Image();
img.onload = (e) => {
  canvas.width = img.width;
  canvas.height = img.height;
  animate();
};
img.src = "https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg";

function animate() {
  // animate 'pow' back and forth
  pow = pow + speed;
  if( pow >= 5 || pow <= -2 ) { speed *= -1; }
  // we'll use the SVG filter on our context
  ctx.filter = 'url(#sharp)';
  // set the matrix as you wish, here I just gather all closest to the center
  matrix.setAttribute( 'kernelMatrix',
    pow * 1 + ' ' + pow *  1 + ' ' + pow * -1 + ' ' +
    pow * 1 + ' ' + 1 + ' ' + pow * -1 + ' ' +
    pow * 1 + ' ' + pow * -1 + ' ' + pow * -1
  );

  ctx.drawImage( img, 0, 0 );
  ctx.filter = 'none';
  
  requestAnimationFrame( animate );
}
<svg width="0" height="0" style="position:absolute;z-index: -1">
  <filter id="sharp">
    <feConvolveMatrix id="conv-matrix"
      kernelMatrix="
         1  1 -1
         1  1 -1 
         1 -1 -1
     "/>
  </filter>
</svg>
<canvas id="canvas"></canvas>


相关问题