我正在尝试创建一个代码,在该代码中以随机颜色在屏幕上随机绘制一个笑脸,该颜色应该循环播放,但是我不知道如何最好地使用random()函数来完成此操作。谁能给我一些指导!我试过使用变量(在draw函数中使用var来调用函数smileyFace,但是没有运气!
代码:
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>
答案 0 :(得分:2)
[...]在一张画布上随机绘制颜色(r,g,b)并在屏幕上随机放置多个笑脸。
只需将调用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>
{{1}}
答案 1 :(得分:2)
p5中的draw()
函数执行多次,因此,如果要绘制多张笑脸,可以将smileyFace()
方法放入draw()
方法中。
要获得随机颜色,可以将color
对象传递给fill(color)
方法。要获得颜色,可以使用color()
方法,该方法接受三个值。值是r
(红色),g
(绿色)和b
(蓝色),并且必须介于0-255之间。因此,要获得随机颜色,可以使用random(0, 255)
为每个颜色分量(r,g和b)获取随机值:
function setup() {
createCanvas(400, 400);
background(220);
}
function draw() {
smileyFace(random(0, 400), random(0, 400));
}
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>