Saturday, September 6, 2025
HomeLanguagesJavascriptp5.Color setAlpha() Method

p5.Color setAlpha() Method

The setAlpha() method in p5.js is used to set the alpha component of a p5.Color object. The range of the alpha value is dependent on the current color mode. In the default RGB color mode, the value can be between 0 and 255.

Syntax:

setAlpha( alpha )

Parameters: This method accepts a single parameter as mentioned above and described below:

  • alpha: It is a number that denotes the new alpha value.

The example below illustrates the setAlpha() method in p5.js:

Example 1:

Javascript




function setup() {
  createCanvas(600, 300);
  
  alphaSlider = createSlider(0, 255, 128);
  alphaSlider.position(30, 50);
}
  
function draw() {
  clear();
  textSize(18);
  
  // Get the alpha value from the slider
  let alphaValue = alphaSlider.value();
  
  let newColor = color(128, 255, 128);
  
  // Set the alpha value of the color
  newColor.setAlpha(alphaValue);
    
  background(newColor);
  fill('black');
  text("Move the slider to change the " +
       "alpha component of the background color",
       20, 20);
    
}


Output:

Example 2:

Javascript




function setup() {
  createCanvas(600, 300);
  
  alphaSlider = createSlider(0, 255, 128);
  alphaSlider.position(30, 50);
}
  
function draw() {
  clear();
  textSize(18);
  
  noFill();
  stroke(0);
  strokeWeight(50);
  ellipse(width / 2, height / 2, 150);
  strokeWeight(1);
  
  // Get the alpha value from the slider
  let alphaValue = alphaSlider.value();
  
  let newColor = color(255, 128, 128);
  
  // Set the alpha value of the color
  newColor.setAlpha(alphaValue);
    
  noStroke();
  background(newColor);
  fill('black');
  text(
    "Move the slider to change the " +
    "alpha component of the background color",
    20, 20);
    
}


Output:

Online editor: https://editor.p5js.org/

Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

Reference: https://p5js.org/reference/#/p5.Color/setAlpha

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11868 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS