我有以下代码
var bubbles = [];
function setup(){
createCanvas(600, 400);
for (let i = 0; i < 5; i++) {
let x = random(width);
let y = random(height);
let r = random(10, 50);
bubbles.push(new Bubble(x, y, r));
}
}
function draw(){
background(0);
for(let i = 0; i < bubbles.length; i++){
bubbles[i].move();
bubbles[i].display();
}
}
//When mouse over any bubbles, I want to call function coverColor()**
function mouseMoved(){
for(let i = 0; i < bubbles.length; i++){
bubbles[i].coverColor();
}
}
class Bubble {
constructor(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
//Specify the coordinates of the mouse cursor so that when the mouse over bubbles, the bubble will change color:**
coverColor() {
let d = dist( mouseX, mouseY, this.x, this.y);
if (d < this.r){
fill(102, 102, 255);
}
}
//function display() already had the fill(color)**
display() {
stroke(0, 191, 255);
strokeWeight(2);
fill(255, 51, 51); //this one**
ellipse(this.x, this.y, this.r*2);
}
move() {
this.x = this.x + random(1, -1);
this.y = this.y + random(1, -1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
我正在尝试寻找以下问题的答案:
- 当我将鼠标悬停在气泡上时,它不会更改为新颜色,我希望
mouseMove()
有效。 - 当成功更改颜色时,我想在鼠标悬停时独立更改每个气泡的颜色(现在它会更改所有气泡,尽管我只将鼠标放在一个气泡上)
最佳答案
向 Bubble
类添加一个属性,用于说明气泡是否被触摸 (this.hit
):
class Bubble {
constructor(x, y, r){
// [...]
this.hit = false;
}
// [...]
根据绘制气泡时的状态设置填充颜色:
class Bubble {
// [...]
display() {
// [...]
if (this.hit) {
fill(102, 102, 255);
} else {
noFill();
}
ellipse(this.x, this.y, this.r*2);
}
当鼠标悬停在气泡上时更改状态。如果鼠标“离开”气泡,您可以选择重置状态:
class Bubble {
// [...]
coverColor() {
let d = dist( mouseX, mouseY, this.x, this.y);
if (d < this.r){
this.hit = true;
} else {
// this code would cancel the "hit" state, when the mouse leaves the bubble
// this.hit = false;
}
}
// [...]
参见示例:
var bubbles = [];
function setup(){
createCanvas(600, 400);
for (let i = 0; i < 5; i++) {
let x = random(width);
let y = random(height);
let r = random(10, 50);
bubbles.push(new Bubble(x, y, r));
}
}
function draw(){
background(0);
for(let i = 0; i < bubbles.length; i++){
bubbles[i].move();
bubbles[i].display();
}
}
function mouseMoved(){
for(let i = 0; i < bubbles.length; i++){
bubbles[i].coverColor();
}
}
class Bubble {
constructor(x, y, r){
this.x = x;
this.y = y;
this.r = r;
this.hit = false;
}
coverColor() {
let d = dist( mouseX, mouseY, this.x, this.y);
if (d < this.r){
this.hit = true;
} else {
// this code would cancel the "hit" state, when the mouse leaves the bubble
// this.hit = false;
}
}
display() {
stroke(0, 191, 255);
strokeWeight(2);
if (this.hit) {
fill(102, 102, 255);
} else {
noFill();
}
ellipse(this.x, this.y, this.r*2);
}
move() {
this.x = this.x + random(1, -1);
this.y = this.y + random(1, -1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
关于javascript - 预定义函数 display() 时如何覆盖效果并更改数组每个元素中的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60180726/