在p5.js中使用random()函数

问题描述 投票:0回答:2

我正在尝试创建一个代码,在该代码中以随机颜色在屏幕上随机绘制一个笑脸,该颜色应该循环播放,但是我不知道如何最好地使用random()函数来完成此任务。谁能给我一些指导!我尝试使用变量(在draw函数中的var调用函数smileyFace,但是没有运气!

CODE:

function setup() {
  createCanvas(400, 400);
  background(220);
  smileyFace(random(0, 400), random(0, 400));
}

function draw() {

}

function smileyFace(x, y) {
  fill(250);
  ellipse(x, y, 60, 60);
  fill(255);
  ellipse(x - 10, y - 10, 10, 10);
  ellipse(x + 10, y - 10, 10, 10);
  arc(x, y + 5, 30, 25, 0, PI, CHORD);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
javascript random p5.js
2个回答
1
投票

p5中的draw()函数执行多次,因此,如果要绘制多张笑脸,可以将smileyFace()方法放置在draw()方法中。

要获得随机颜色,您可以将color对象传递给fill(color)方法。要获得颜色,可以使用color方法,该方法接受三个值。值是rgb,并且必须介于0-255之间,因此您可以使用random(0, 255)获取每个颜色分量的随机值:

function setup() {
  createCanvas(400, 400);
  background(220);
}

function draw() {
  smileyFace(random(0, 400), random(0, 400));
  frameRate(5); // runs at 5 frames per second
}

function smileyFace(x, y) {
  fill(getRandomColour());
  ellipse(x, y, 60, 60);
  
  fill(getRandomColour());
  ellipse(x - 10, y - 10, 10, 10);
  ellipse(x + 10, y - 10, 10, 10);
  arc(x, y + 5, 30, 25, 0, PI, CHORD);
}

function getRandomColour() {
  const r = random(0, 255);
  const g = random(0, 255);
  const b = random(0, 255);
  return color(r, g, b);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

0
投票

[...]在一张画布上随机绘制颜色(r,g,b)并在屏幕上随机放置的多个笑脸。

只需将调用smileyFace移动到draw函数并通过以下方式创建随机颜色

c = color(random(0, 255), random(0, 255), random(0, 255));

请参见示例:

function setup() {
    createCanvas(400, 400);
    background(220);
}

function draw() {
    c = color(random(0, 255), random(0, 255), random(0, 255));
    smileyFace(random(0, 400), random(0, 400), c);
}

function smileyFace(x, y, c) {
    fill(c);
    ellipse(x, y, 60, 60);
    fill(255);
    ellipse(x - 10, y - 10, 10, 10);
    ellipse(x + 10, y - 10, 10, 10);
    arc(x, y + 5, 30, 25, 0, PI, CHORD);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.