Skip to main content

HTML5 Canvas RGB 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 change rgb components of an image with Konva, we can use the Konva.Filters.RGB.

Instructions: Slide the controls to change RGB 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.RGB]);
  image.red(100);
  image.green(100);
  image.blue(100);

  // create sliders
  const createSlider = (label, 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 = '0';
    slider.max = '255';
    slider.step = '1';
    slider.value = image[property]();
    slider.style.width = '200px';
    
    slider.addEventListener('input', (e) => {
      const value = parseInt(e.target.value);
      image[property](value);
      layer.batchDraw();
    });
    
    container.appendChild(slider);
    return container;
  };

  const redSlider = createSlider('Red', 'red');
  redSlider.style.top = '20px';
  document.body.appendChild(redSlider);

  const greenSlider = createSlider('Green', 'green');
  greenSlider.style.top = '45px';
  document.body.appendChild(greenSlider);

  const blueSlider = createSlider('Blue', 'blue');
  blueSlider.style.top = '70px';
  document.body.appendChild(blueSlider);
};
imageObj.src = '/images/lion.png';