Skip to main content

HTML5 Canvas Hue, Saturation and Value filter Image Tutorial

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

To change hue, saturation and value components of an image with Konva, we can use the Konva.Filters.HSV.

Instructions: Slide the controls to change HSV values.

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.HSV]);
  
  // create sliders
  const createSlider = (label, min, max, defaultValue, property) => {
    const container = document.createElement('div');
    container.style.position = 'absolute';
    container.style.left = '20px';
    
    const text = document.createElement('span');
    text.textContent = `${label}: `;
    container.appendChild(text);
    
    const slider = document.createElement('input');
    slider.type = 'range';
    slider.min = min;
    slider.max = max;
    slider.step = '0.1';
    slider.value = defaultValue;
    slider.style.width = '200px';
    
    slider.addEventListener('input', (e) => {
      const value = parseFloat(e.target.value);
      image[property](value);
      layer.batchDraw();
    });
    
    container.appendChild(slider);
    return container;
  };

  const hueSlider = createSlider('Hue', -180, 180, 0, 'hue');
  hueSlider.style.top = '20px';
  document.body.appendChild(hueSlider);

  const saturationSlider = createSlider('Saturation', -2, 10, 0, 'saturation');
  saturationSlider.style.top = '45px';
  document.body.appendChild(saturationSlider);

  const value = createSlider('Value', -2, 2, 0, 'value');
  value.style.top = '70px';
  document.body.appendChild(value);
};
imageObj.src = 'https://new.konvajs.org/assets/lion.png';
imageObj.crossOrigin = 'anonymous';