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

时间:2017-01-27 18:35:40

标签: javascript canvas processing paint p5.js

我一直在使用p5.js创建一个简单的绘图程序。到目前为止,我创建了我的绘画调色板,我可以在画布上绘图。我需要帮助使用mouseIsPressed方法更改调色板颜色。我想点击一种颜色然后在我的画布上画画。这是我到目前为止所做的。

console.log(`${title} loop ${type} time:  ${date[type]}`);

1 个答案:

答案 0 :(得分:0)

这里你去:

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;
};

当鼠标超过某个矩形时,collide函数返回true,否则返回false。这样你可以使用if (collide( **x and y coordinates of rect** )) {}做某事,在这种情况下定义一个变量。希望这对你有所帮助,祝你有个美好的一天。

另请注意,碰撞函数采用矩形的左上角x和y。

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

相关问题