Skip to main content

HTML5 Canvas Pixelate 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 pixelate effect of an image with Konva, we can use the Konva.Filters.Pixelate.

Instructions: Slide the control to change pixel size 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.Pixelate]);
  image.pixelSize(8);

  // 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 = 'Pixel Size: ';
  container.appendChild(text);
  
  const slider = document.createElement('input');
  slider.type = 'range';
  slider.min = '2';
  slider.max = '32';
  slider.step = '1';
  slider.value = image.pixelSize();
  slider.style.width = '200px';
  
  slider.addEventListener('input', (e) => {
    const value = parseInt(e.target.value);
    image.pixelSize(value);
    layer.batchDraw();
  });
  
  container.appendChild(slider);
  document.body.appendChild(container);
};
imageObj.src = '/images/lion.png';