Reputation: 55
I am trying to expand on an example my tutor used to introduce P5.js so I would like to try and have the color change each time (within the square) to a color I have pre-set on loop rather than it being randomised.
I've tried changing things around like adding a second line of fill (above (rect (sx, ry, w, squareDim) ;) but so far it remains the same, Blue to Black and repeat.
For example, I would like to have it go from blue to red, orange and purple for example then back to black (the start)
Any input or possible suggestions would be very much appreciated!!:)
var squareDim = 500;
var colourlapse;
var rx = 50;
var ry = 50;
var inc = 0.009;
function setup() {
frameRate(49);
//put setup code here
createCanvas(700, 700);
colourlapse = 0.0;
}
function draw() {
// put drawing code here
var w = colourlapse * squareDim;
var sx;
sx = rx;
if (inc > 0) {
sx = rx
} else {
sx = rx + squareDim - w;
}
background(255);
stroke(255);
fill(0);
rect(rx, ry, squareDim, squareDim);
fill(0, 0, 255);
rect(sx, ry, w, squareDim);
colourlapse += inc;
if (colourlapse >= 1) {
colourlapse = 1;
inc *= -1;
} else if (colourlapse <= 0) {
colourlapse = 0;
inc *= -1;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
Upvotes: 3
Views: 2899
Reputation: 210889
You've to define a list of colors and 2 variables which contain the index of the current color:
let colors = [[0, 0, 0], [0, 0, 255], [0, 255, 0], [255, 0, 0]]
let cur_col1 = 1;
let cur_col2 = 0;
Th indices of the colors are incremented every time when the line reaches the start or end of the region. Use the modulo operator to limit the index to the bounds of the array of colors:
fill(...colors[cur_col1 % colors.length]);
While the with of the 1st rectangle is w
, the width of the 2nd rectangle is squareDim-w
. The starting x-coordinate of the 2nd rectangle is either the end of the 1st rectangle
(rx + w
) or the start of the area (rx
):
var sx1 = (inc > 0) ? rx : rx + squareDim - w;
var sx2 = (inc > 0) ? rx + w : rx;
See the example:
var rectWidth = 500;
var rectHeight = 300;
var colourlapse;
var rx = 50;
var ry = 50;
var inc = 0.009;
let colors = [[0, 0, 0], [0, 0, 255], [0, 255, 0], [255, 0, 0]]
let cur_col1 = 1;
let cur_col2 = 0;
function setup() {
frameRate(49);
createCanvas(700, 700);
colourlapse = 0.0;
}
function draw() {
var w = colourlapse * rectWidth;
var sx1 = (inc > 0) ? rx : rx + rectWidth - w;
var sx2 = (inc > 0) ? rx + w : rx;
background(0);
stroke(255);
fill(0);
fill(...colors[cur_col1 % colors.length]);
rect(sx1, ry, w, rectHeight);
fill(...colors[cur_col2 % colors.length]);
rect(sx2, ry, rectWidth-w, rectHeight);
colourlapse += inc;
if (colourlapse >= 1) {
colourlapse = 1;
inc *= -1;
cur_col2 += 2;
} else if (colourlapse <= 0) {
colourlapse = 0;
inc *= -1;
cur_col1 += 2;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
Upvotes: 3