我认为我的代码应该更改 exampleoutput 但它显示 0 (我在 p5.js 上运行它)。我将第 6 行上的
outputVar=1;
更改为 exampleoutput=1;
,它有效,但我希望能够更改它。
我的代码:
var exampleoutput = 0;
var makeButton = function (
x1,
x2,
y1,
y2,
outputVar,
haveShape,
colorR,
colorG,
colorB
) {
mouseClicked = function () {
if (mouseX >= x1 && mouseX <= x2 && mouseY >= y1 && mouseY <= y2) {
outputVar = 1;
}
};
if (haveShape === 1) {
fill(colorR, colorG, colorB);
rect(x1, y1, x2 - x1, y2 - y1);
}
};
function draw() {
background(255, 255, 255);
makeButton(50, 100, 50, 100, exampleoutput, 1, 0, 0, 0);
fill(0, 0, 0);
text(exampleoutput, 200, 200);
}
向“按钮”添加点击“侦听器”(使用引号是因为当您使用画布时这些概念实际上并不存在 - 考虑使用实际 DOM 按钮)可以通过添加单个
来完成mouseClicked
全局功能:
const x1 = 50;
const x2 = 100;
const y1 = 50;
const y2 = 100;
let isButtonClicked = false;
function mouseClicked() {
if (
mouseX >= x1 &&
mouseX <= x2 &&
mouseY >= y1 &&
mouseY <= y2
) {
isButtonClicked = true;
}
}
function draw() {
background(255, 255, 255);
rect(x1, y1, x2 - x1, y2 - y1);
fill(0, 0, 0);
text(isButtonClicked ? "yes" : "no", 20, 20);
fill(0, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/p5.js"></script>
或者在
mouseIsPressed
循环中使用 draw()
:
const x1 = 50;
const x2 = 100;
const y1 = 50;
const y2 = 100;
function buttonClicked() {
return (
mouseX >= x1 &&
mouseX <= x2 &&
mouseY >= y1 &&
mouseY <= y2
);
}
function draw() {
background(255, 255, 255);
rect(x1, y1, x2 - x1, y2 - y1);
fill(0, 0, 0);
const t = mouseIsPressed && buttonClicked() ? "yes" : "no";
text(t, 20, 20);
fill(0, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/p5.js"></script>