使用 p5.js 的简单画图程序

Simple Paint Program using p5.js

我一直致力于使用 p5.js 创建一个简单的绘图程序。到目前为止,我创建了自己的调色板,并且可以在我的 canvas 上作画。我需要有关使用 mouseIsPressed 方法更改调色板颜色的帮助。我想点击一种颜色,然后在我的 canvas 上画画。这是我目前所拥有的。

function setup(){
createCanvas(500,500);
}

function draw() {
noStroke();
//red
fill(255,0,0);
rect(0,0,20,20);
//orange
fill(255,165,0);
rect(0,20,20,20);
//yellow
fill(255,255,0);
rect(0,40,20,20);
//green
fill(0,255,0);
rect(0,60,20,20);
//cyan
fill(0,255,255);
rect(0,80,20,20);
//blue
fill(0,0,255);
rect(0,100,20,20);
//magenta
fill(255,0,255);
rect(0,120,20,20);
//brown
fill(165,42,42);
rect(0,140,20,20);
//white
fill(255);
rect(0,160,20,20);
//black
fill(0);
rect(0,180,20,20);

if(mouseIsPressed ){
  if(mouseIsPressed && mouseX == 0 && mouseY == 0){
    strokeWeight(10);
    stroke(0);
    line(pmouseX,pmouseY,mouseX,mouseY);
  }
 }
}

给你:

var selected;

function setup(){
createCanvas(500,500);
}

function draw() {
noStroke();
//red
fill(255,0,0);
rect(0,0,20,20);
//orange
fill(255,165,0);
rect(0,20,20,20);
//yellow
fill(255,255,0);
rect(0,40,20,20);
//green
fill(0,255,0);
rect(0,60,20,20);
//cyan
fill(0,255,255);
rect(0,80,20,20);
//blue
fill(0,0,255);
rect(0,100,20,20);
//magenta
fill(255,0,255);
rect(0,120,20,20);
//brown
fill(165,42,42);
rect(0,140,20,20);
//white
fill(255);
rect(0,160,20,20);
//black
fill(0);
rect(0,180,20,20);
}

function mousePressed (){
  if(collide(0, 0)){
    selected = "red";
  }else if(collide(0, 20)){
    selected = "orange";
  }else if(collide(0, 40)){
    selected = "yellow";
  }//and so on...
}

function collide ( x, y) {
//2d
if (mouseX >= x &&         // right of the left edge AND
    mouseX <= x + 20 &&    // left of the right edge AND
    mouseY >= y &&         // below the top AND
    mouseY <= y + 20) {    // above the bottom
        return true;
}
return false;
};

碰撞函数returns 当鼠标在某个矩形上时为真,否则为假。这样你就可以使用 if (collide( **x and y coordinates of rect** )) {} 来做一些事情,在这种情况下定义一个变量。希望对你有帮助,祝你有个愉快的一天。

另请注意,碰撞函数采用矩形的 top-left 角 x 和 y。

mousePressed 的使用https://p5js.org/reference/#/p5.Element/mousePressed