gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:26:47 25 4
gpt4 key购买 nike

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

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

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

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>

最佳答案

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

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

每当线条到达区域的起点或终点时,颜色的索引都会递增。使用模运算符将索引限制在颜色数组的范围内:

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

第一个矩形的宽度是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>

关于javascript - 正方形内的多种颜色变化(填充)(P5.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com