Search code examples
arraystransparencyp5.js

Changing opacity of each shape seperately in an array p5.js


I'm new to coding. I created a simple code and I need help with targeting each of the elements (each rectangle) in the array seperately. My goal is to change the opacity or transparency of each of the rectangles.

I can simply do fill(0, 255, 100, 50)and add an alpha value but this changes all of the rectangles.. I want to change the transparency - Alpha values: 50, 100, 150, 200, 250 respectively for each rectangle. I tried to create an array for it and implement it to the rectangles but I can't seem to do it.

Here is the code, any help is appreciated :)

function setup() {
      createCanvas(500, 110);
    }
    function draw() {
  background(0, 100, 180);
  stroke(2);
  rectMode(CENTER);
  
  for (var i = 0; i < 5; i++) {
    fill(0,255, 100);
    rect((i+1)*80, 50, 50, 50, 15);
    
  }
}

Solution

  • You can dynamically define a color (including alpha attribute) using the color() function.

    Here is a working example: https://editor.p5js.org/chen-ni/sketches/aWnKXEYh1

    var alphaValues = [50, 100, 150, 200, 250];
    
    function setup() {
      createCanvas(500, 110);
    }
    
    function draw() {
      background(0, 100, 180);
      stroke(2);
      rectMode(CENTER);
    
      for (var i = 0; i < alphaValues.length; i++) {
        var _alpha = alphaValues[i];
        var _color = color(0, 255, 100, _alpha);
        fill(_color);
        rect((i + 1) * 80, 50, 50, 50, 15);
      }
    }