Skip to main content

HTML5 Canvas Threshold filter Image Tutorial

To apply filter to an Konva.Image, we have to cache it first with cache() function. Then apply filter with filters() function.

To apply a threshold effect to an image with Konva, we can use the Konva.Filters.Threshold. The threshold filter converts the image into a black and white image where all pixels above the threshold value become white and all pixels below become black.

Instructions: Slide the control to change threshold value.

For all available filters go to Filters Documentation.

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);

  // create slider
  const container = document.createElement('div');
  container.style.position = 'absolute';
  container.style.top = '20px';
  container.style.left = '20px';
  
  const text = document.createElement('span');
  text.textContent = 'Threshold: ';
  container.appendChild(text);
  
  const slider = document.createElement('input');
  slider.type = 'range';
  slider.min = '0';
  slider.max = '1';
  slider.step = '0.01';
  slider.value = image.threshold();
  slider.style.width = '200px';
  
  slider.addEventListener('input', (e) => {
    const value = parseFloat(e.target.value);
    image.threshold(value);
    layer.batchDraw();
  });
  
  container.appendChild(slider);
  document.body.appendChild(container);
};
imageObj.src = '/images/lion.png';