如何在p5.js中保持随机颜色?
我刚刚开始学习p5.js,我有一个随机颜色的问题。现在,我看到只有在重新启动代码时,颜色才会随机重置。但是,每当鼠标按下时,是否可以使它发生?
这是我的代码:
let r, g, b;
function setup() {
createCanvas(400, 400);
r = random(255);
g = random(255);
b = random(255);
}
function draw() {
if (mouseIsPressed) {
fill(r,g,b);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
I just started learning p5.js myself and I have a question with randomizing colors. Right now I see that the color will be reset randomly only when I restart the code. But is it possible to make it happen whenever mouse is pressed?
Here is my code:
let r, g, b;
function setup() {
createCanvas(400, 400);
r = random(255);
g = random(255);
b = random(255);
}
function draw() {
if (mouseIsPressed) {
fill(r,g,b);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须创建新的
r
,g
和b
值,当按下鼠标时:You have to create new
r
,g
andb
values when the mouse is pressed:rabbid76是正确的,您需要覆盖
r
,g
g ,b
变量如果您的目标是在发布鼠标后持续存在这些值,但是我建议在Mousepressed
全局功能中进行此操作,以便多个触发器不会发生。Rabbid76 is right that you need to overwrite the
r
,g
,b
variables if your goal is to persist those values after the mouse is released, but I'd suggest doing it inside themousePressed
global function so that multiple triggers won't occur.