p5.js中构造函数类用布尔值实现点击矩形变色与状态切换问题
p5.js 矩形点击切换颜色与状态问题解决
核心问题修正
1. 类构造函数中数组声明
p5.js 里类的构造函数中声明数组和常规 JS 类写法一致,直接通过 this.数组名 定义即可,比如颜色数组可以这么写:
this.colors = [color(255, 0, 0), color(0, 255, 0)];
不用纠结 Processing 的写法,按 JS 类的规则来就行。
2. 点击同步切换逻辑
要实现点击矩形时同时切换状态和颜色,需要做三件事:
- 给类添加点击检测方法,判断鼠标是否在矩形范围内
- 检测到点击时同时更新状态变量和当前颜色
- 在全局的
mousePressed()函数中调用类的点击处理方法
完整示例代码
class Square { constructor(x, y, size) { this.x = x; this.y = y; this.size = size; // 构造函数中正确声明颜色数组 this.colors = [color(255, 0, 0), color(0, 255, 0)]; // 状态变量:0为初始态,1为切换态 this.state = 0; // 绑定当前颜色与状态 this.currentColor = this.colors[this.state]; } // 绘制矩形 display() { fill(this.currentColor); rect(this.x, this.y, this.size, this.size); } // 点击检测与状态切换 clicked() { // 判断鼠标是否在矩形区域内 if (mouseX > this.x && mouseX < this.x + this.size && mouseY > this.y && mouseY < this.y + this.size) { // 切换状态 this.state = this.state === 0 ? 1 : 0; // 同步更新颜色 this.currentColor = this.colors[this.state]; } } } let square; function setup() { createCanvas(400, 400); square = new Square(100, 100, 200); } function draw() { background(220); square.display(); } // 全局鼠标点击事件触发类的点击处理 function mousePressed() { square.clicked(); }
关键说明
- 不要在类内部尝试监听鼠标事件,p5.js 的鼠标事件是全局触发的,需要在全局函数中调用类的方法
- 状态和颜色的绑定要同步,每次状态切换时直接从数组中取对应颜色赋值给当前颜色变量
- 如果是多个矩形,只需要把单个 Square 改成数组存储,在
mousePressed()里遍历数组调用每个元素的clicked()方法即可
内容的提问来源于stack exchange,提问作者Alèn Martel
相关产品推荐
相关产品推荐

