Skip to main content

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

Instructions: Slide the control to change noise 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.Noise]);
  image.noise(0.3);

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