Skip to main content

HTML5 Canvas Kaleidoscope Image Filter Tutorial

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

To create a kaleidoscope with Konva, we can use the Konva.Filters.Kaleidoscope filter and set the kaleidoscopePower and kaleidoscopeAngle properties.

Instructions: Slide the controls to adjust the kaleidoscope power and angle.

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.Kaleidoscope]);
  image.kaleidoscopePower(3);
  image.kaleidoscopeAngle(0);

  // 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 = property === 'kaleidoscopePower' ? '1' : '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 powerSlider = createSlider('Power', 2, 8, 3, 'kaleidoscopePower');
  powerSlider.style.top = '20px';
  document.body.appendChild(powerSlider);

  const angleSlider = createSlider('Angle', 0, 360, 0, 'kaleidoscopeAngle');
  angleSlider.style.top = '45px';
  document.body.appendChild(angleSlider);
};
imageObj.src = '/images/lion.png';