Open In App

p5.js filter() Function

The filter() function is used to apply filters to the canvas. p5.js has several presets that can be used with different levels of intensity to get the desired effect.
Syntax: 
 

filter( filterType, filterParam)

Parameters: This function accept two parameters as mentioned above and described below: 
 



Below examples illustrate the filter() function in p5.js:
Example 1:
 




function preload() {
  img = loadImage("sample-image.png");
}
  
function setup() {
  filterModes = [
    GRAY,
    OPAQUE,
    INVERT,
    POSTERIZE,
    BLUR,
    ERODE,
    DILATE,
    BLUR,
    THRESHOLD
  ];
  
  index = 0;
  currFilterMode = filterModes[index];
  
  createCanvas(500, 300);
  textSize(20);
  
  btn = createButton("Change filter");
  btn.position(30, 200);
  btn.mousePressed(changeFilter);
}
  
function draw() {
  clear();
  
  text('Click on the button to change the filter mode', 20, 20);
  text("Current filter: " + currFilterMode, 20, 50);
  
  image(img, 20, 80);
  
  // Set the filter
  filter(currFilterMode);
}
  
function changeFilter() {
  if (index < filterModes.length - 1)
    index++;
  else
    index = 0;
  currFilterMode = filterModes[index];
  
  console.log("Current filter: " + currFilterMode);
}

Output: 
 



Example 2: 
 




let level = 0;
  
function preload() {
  img = loadImage("sample-image.png");
}
  
function setup() {
  createCanvas(500, 300);
  textSize(20);
  
  valueSlider = createSlider(0, 3, 0, 0.1);
  valueSlider.position(30, 200);
  valueSlider.input(changeLevel);
}
  
function draw() {
  clear();
  
  text('Move the slider to change the blur radius', 20, 20);
  text("Current radius: " + level + "m", 20, 50);
  
  image(img, 20, 80);
  
  // Set the filter
  filter(BLUR, level);
}
  
function changeLevel() {
  level = valueSlider.value();
}

Output: 
 

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/amp/
Reference: https://p5js.org/reference/#/p5/filter
 


Article Tags :