如何为背景设置变量以稍后更改它,而无需绘制背景?我想将其保留在设置中,这样它就不会重新绘制



这是一个包含改变颜色的旋转圆圈代码。我希望能够将背景从白色改为黑色,稍后在绘制中使用mouseOver函数,但我不能这样做,除非'bg'变量在绘制中。有没有一种方法来保持它的设置,所以我可以离开彩虹的踪迹,而仍然改变颜色为黑色?

这是我到目前为止的代码:

let bg = 255
let hueV2 = 0
let position = 0
function setup() {
createCanvas(500, 500)
background(bg)
}
function draw() {
console.log(mouseX, mouseY);
colorMode(HSL);
//circle with rainbow trail
strokeWeight(13);
stroke(hueV2, 90, 61)
hueV2 = hueV2 + 1
arc(410, 240, 50, 50, position, position + 0.001, OPEN);
position += 2.5
if (hueV2 >= 360) {
hueV2 = 0
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>

不完全遵循-不确定这是否是某种框架或什么-但以防它在任何方面有所帮助。

  1. 用你想要的任何颜色初始化背景。黑色的。
  2. 然后,在draw()方法上有一个bool,当鼠标结束时注册。
  3. 如果为true (mouseOver),则交换颜色到某个东西;如果为false,则交换颜色到其他东西。
  4. 否则

:

  1. 在setup()
  2. 中初始化背景
  3. 稍后在draw()中切换为黑色如果!= 0(或者如果鼠标在触发器上)

抱歉,如果我匆忙回答这里,但我有点不明白为什么你不能在draw()或任何其他变量中使用bg。

这似乎是你想要的工作:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<title></title>
</head>
<body>
<script>
let bg = 255
let hueV2 = 0
let position = 0
let swap=true
function setup() {
createCanvas(500, 500)
background(bg)
}
function renderstuff() {

//circle with rainbow trail
strokeWeight(13);
stroke(hueV2, 90, 61)
hueV2 = hueV2 + 1
arc(410, 240, 50, 50, position, position + 0.001, OPEN);
position += 2.5
if (hueV2 >= 360) {
hueV2 = 0
}
}
function draw() {
console.log(mouseX, mouseY);
colorMode(HSL);

if (swap==true){
background(0)
swap=false
}
renderstuff()
}
</script>
</body>
</html>

最新更新