因此,在p5js编辑器中,我试图使用正方形可视化二维数组。我希望一个正方形通过mousPressed()改变颜色,具体取决于鼠标相对于正方形的坐标。我正在改变颜色,但是单击的方块不是改变的方块。
我正在记录我要单击的节点,看来它是正确的,但是2d数组的可视化似乎是错误的。
我有一个正方形x的3x3网格,使得:
x x x
x x x
x x x
我希望当我单击左上角然后单击中上角时,它将颜色更改为蓝色,从而使
o x
x x x
x x x
但是当我单击左上角然后单击中上角时,我得到
x o o
x x x
x x x
似乎单击的正方形将更改其旁边的正方形,而不是我期望的正方形。
p5.editor中的示例:https://editor.p5js.org/julien24lopez/present/8_vwyHTjRW
let arr = [];
function setup(){
canvas = createCanvas(200, 200);
for(var j = 0; j < 3; j++){
var inArr = [];
for(var i = 0; i < 3; i++){
var rect = new Rect(i,j);
inArr.push(rect);
}
arr.push(inArr)
}
}
function draw(){
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
arr[i][j].show()
}
}
}
function mousePressed(){
arr.forEach(function(e, index){
e.forEach(function(d,index2){
arr[index][index2].clicked()
});
});
}
function Rect(i,j){
this.fill = 'red'
this.i = i;
this.j = j;
this.x = i * 20
this.y = j * 20
this.clicked = function(){
let x1 = this.x, x2 = x1 + 20,
y1 = this.y, y2 = y1 + 20;
if((mouseX>x1&&mouseX<x2)&&(mouseY>y1&&mouseY< y2)){
console.log(this)
this.fill = 'black'
}
}
this.show = function(){
rect(i*20,j*20,20,20)
fill(this.fill)
stroke('blue')
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
您未在正确的位置绘制四边形。四边形的位置是(this.x, this.y)
,而不是(i*20, j*20)
:
function Rect(i,j){
// [...]
this.show = function(){
fill(this.fill)
stroke('blue')
// rect(i*20,j*20,20,20)
rect(this.x, this.y, 20, 20)
}
}
示例:
let arr = [];
function setup(){
canvas = createCanvas(200, 200);
for(var j = 0; j < 3; j++){
var inArr = [];
for(var i = 0; i < 3; i++){
var rect = new Rect(i,j);
inArr.push(rect);
}
arr.push(inArr)
}
}
function draw(){
background(255);
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
arr[i][j].show()
}
}
}
function mousePressed(){
arr.forEach(function(e, index){
e.forEach(function(d,index2){
arr[index][index2].clicked()
});
});
}
function Rect(i,j){
this.fill = 'red'
this.i = i;
this.j = j;
this.x = i * 20
this.y = j * 20
this.clicked = function(){
let x1 = this.x, x2 = x1 + 20,
y1 = this.y, y2 = y1 + 20;
if( mouseX > x1 && mouseX < x2 && mouseY > y1 && mouseY < y2){
console.log(this)
this.fill = 'black'
}
}
this.show = function(){
fill(this.fill)
stroke('blue')
rect(this.x, this.y, 20, 20)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>