我试图为每个圆圈分配一次随机颜色,然后让该颜色在色谱中不断变化。我是一个初学者,无法弄清楚如何阻止绘制函数中的随机颜色重置每个循环,而不将其拉入设置函数,然后使所有圆圈从相同的随机颜色开始。下面是我到目前为止所拥有的代码。目前它似乎也在轻微地改变颜色,我认为这与“for”有关。我想要的只是一个圆圈网格,这些圆圈被分配了一次随机颜色,然后继续以相同的速度通过色轮来处理它们的颜色。提前致谢!
let intervals = [10];
let count;
let frameWidth;
let distance;
let diam1;
let col1;
let sat1;
let bri1;
let speed;
function setup() {
createCanvas(800, 800);
colorMode(HSB, 360, 100, 100, 1);
//initiate draw variables
count = random(intervals);
frameWidth = (width*0.8);
distance = (frameWidth/count);
col1 = random(360);
diam1 = distance*0.5;
speed = 0.005;
}
function draw() {
background(0, 0, 0, 1);
// draw grid of circles
for (let x = width * 0.1; x <= width * 0.9; x += distance) {
for (let y = height * 0.1; y <= height * 0.9; y += distance) {
sat1 = 100;
bri1 = 100;
noStroke();
fill(col1, sat1, bri1, 1);
ellipse(x,y,diam1);
col1 = col1 + speed
if (col1 >= 360) {
col1 = 0
}
}
}
}
最佳答案
您必须在设置
中创建随机颜色网格:
let speed, colors, rows, columns;
function setup() {
// [...]
columns = Math.round(frameWidth / distance) + 1;
rows = Math.round(frameWidth / distance) + 1;
colors = [];
for (let i = 0; i < columns; i ++) {
colors.push([]);
for (let j = 0; j < rows; j ++) {
colors[i].push(random(360));
}
}
speed = 1;
}
在draw
函数中使用colors
。完整示例:
let intervals = [10];
let count, frameWidth, distance;
let sat1, bri1;
let speed, colors, rows, columns, diameters;
function setup() {
createCanvas(800, 800);
colorMode(HSB, 360, 100, 100, 1);
//initiate draw variables
count = random(intervals);
frameWidth = (width*0.8);
distance = (frameWidth/count);
columns = Math.round(frameWidth / distance) + 1;
rows = Math.round(frameWidth / distance) + 1;
colors = [];
diameters = []
for (let i = 0; i < columns; i ++) {
colors.push([]);
diameters.push([]);
for (let j = 0; j < rows; j ++) {
colors[i].push(random(360));
diameters[i].push(random(TWO_PI));
}
}
speed = 1;
}
function draw() {
background(0, 0, 0, 1);
// draw grid of circles
for (let i = 0; i < columns; i ++) {
for (let j = 0; j < rows; j ++) {
sat1 = 100;
bri1 = 100;
noStroke();
fill(colors[i][j], sat1, bri1, 1);
let d = distance * (0.5 + 0.4 * sin(diameters[i][j]));
ellipse(width * 0.1 + i * distance, height * 0.1 + j * distance, d);
colors[i][j] = (colors[i][j] + speed) % 360;
diameters[i][j] = diameters[i][j] + 0.05;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
关于javascript - 如何为网格中的每个圆圈分配随机颜色,然后让每个圆圈从起始颜色开始遍历色谱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69370162/