Skip to main content

HTML5 Canvas 阈值滤镜图像教程

要对 Konva.Image 应用滤镜,我们必须先使用 cache() 函数将其缓存。然后使用 filters() 函数应用滤镜。

为了使用 Konva 对图像应用阈值效果,我们可以使用 Konva.Filters.Threshold。阈值滤镜将图像转换为黑白图像,所有高于阈值的像素变为白色,所有低于阈值的像素变为黑色。

说明:滑动控制以更改阈值。

有关所有可用滤镜的信息,请访问 滤镜文档

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const imageObj = new Image();
imageObj.onload = () => {
  const image = new Konva.Image({
    x: 50,
    y: 50,
    image: imageObj,
    draggable: true,
  });

  layer.add(image);

  image.cache();
  image.filters([Konva.Filters.Threshold]);
  image.threshold(0.5);

  // 创建滑块
  const container = document.createElement('div');
  container.style.position = 'absolute';
  container.style.top = '20px';
  container.style.left = '20px';
  
  const text = document.createElement('span');
  text.textContent = '阈值: ';
  container.appendChild(text);
  
  const slider = document.createElement('input');
  slider.type = 'range';
  slider.min = '0';
  slider.max = '1';
  slider.step = '0.1';
  slider.value = image.threshold();
  slider.style.width = '200px';
  
  slider.addEventListener('input', (e) => {
    const value = parseFloat(e.target.value);
    image.threshold(value);
  });
  
  container.appendChild(slider);
  document.body.appendChild(container);
};
imageObj.src = 'https://konvajs.org/assets/lion.png';
imageObj.crossOrigin = 'anonymous';