正方形(P5.js)内的多种颜色变化(填充)

时间:2019-07-13 23:11:39

标签: p5.js

我正在尝试扩展我的导师用来介绍P5.js的示例,所以我想尝试将颜色(每次在正方形内)更改为我在循环中预先设置的颜色,而不是预先设置的颜色被随机化。

我已经尝试过更改内容,例如添加第二行填充(上方(rect(sx,ry,w,squareDim););但到目前为止,它保持不变,从蓝色变为黑色,然后重复)。

例如,我想让它从蓝色变成红色,橙色和紫色,然后再回到黑色(开始)

任何输入或可能的建议将不胜感激!:)

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>

1 个答案:

答案 0 :(得分:1)

您必须定义颜色列表和2个变量,其中包含当前颜色的索引:

let colors = [[0, 0, 0], [0, 0, 255], [0, 255, 0], [255, 0, 0]]
let cur_col1 = 1;
let cur_col2 = 0;

每当线条到达区域的起点或终点时,颜色的Th指数都会增加。使用模运算符将索引限制为颜色数组的边界:

fill(...colors[cur_col1 % colors.length]);

第一个矩形的with为w时,第二个矩形的宽度为squareDim-w。第二个矩形的起始x坐标是第一个矩形的终点
 (rx + w或区域的开头(rx):

var sx1 = (inc > 0) ? rx : rx + squareDim - w;
var sx2 = (inc > 0) ? rx + w : rx;

请参见示例:

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>