noobiecderssss
noobiecderssss

Reputation: 81

Creating a grid of rectangles that increase in alpha values up to 255 using for loops

I created a grid of rectangles that increase in opacity as you go down and right. I've divided the 256 alpha values evenly into 4 columns (64 rectangles per column).

I'm trying to cut the code down by using for loops for each column.

I've managed to created the column of rectangles, but the fill() for I've setup isn't applying the opacity how I need it to.

Here's what I'm running for column 1:

  for (var a = 0; a < 256; a++) {
    fill(155,0,0,a);
  }

  var y = 0;
  for (var x = 0; y <= 1890; x += 210) {
    for (var y = 0; y <= 1890; y += 30) {
      rect(x,y,200,20)
    }
  }

I've tried combining the fill() and rect() loops, but I get the same issue where the color scale sticks to (155,0,0,255) rather than starting at 0 and going up to 63 (for this column alone).

I'm capped at 4 fill & 4 rect lines in total (e.g. 1 fill-rect-combo per column).

For the complete code and visual representation of the grid, https://codepen.io/anon/pen/KvdJWB

Upvotes: 2

Views: 172

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

The first for loop runs, and finishes, before the nested for loop even starts. You can think about your program as equivalent to this:

  fill(155,0,0,0);
  fill(155,0,0,1);
  fill(155,0,0,2);
  fill(155,0,0,3);
  //...
  fill(155,0,0,254);
  fill(155,0,0,255);


  var y = 0;
  for (var x = 0; y <= 1890; x += 210) {
    for (var y = 0; y <= 1890; y += 30) {
      rect(x,y,200,20)
    }
  }

This makes it obvious that your first for loop isn't really doing much, and only the last call to fill() really matters.

If you want each cell, or each row or column, to be a different color, then you're going to have to call fill() inside the nested for loop somewhere.

Upvotes: 2

Related Questions