绘制矩形,p5.js

Drawing in a rectangle, p5.js

所以我在 p5.js 工作,我的任务是当我按下鼠标时它需要画圆圈,我已经开始工作了。但额外的是,这只能发生在某个矩形中,我有点迷茫,有谁知道我怎么能做到这一点?

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

var circles = [];

function draw() {
  background(220);
  rect(100, 100, 200, 200)
  
  var index = 0;
  while(index < circles.length) {
    ellipse(circles[index].x, circles[index].y, circles[index].d);
      index += 1;
  }
  if (mouseIsPressed) {
    // add a circle where the mouse is
    // not this: ellipse(mouseX, mouseY, 10);
    circles[circles.length] = { x: mouseX, y: mouseY, d: 30 };
  }
} 

这是它需要的样子: enter image description here

现在,无论鼠标在屏幕上的哪个位置,按下鼠标时您的代码都会生成一个圆圈。你想要的是只有当你的鼠标在你的矩形中时才生成新的圆圈,所以这只是添加一个条件来确保你的鼠标不在矩形之外的问题。

要进行此测试,您首先需要知道矩形的边界是什么。您使用 rect(100, 100, 200, 200) 创建它,这意味着左上角位于 x:100, y:100 位置并且它的宽度和长度为 200 因此其右下角位于 x:(100+200)=300, y:(100+200)=300.

所以你只想创建你的圈子是 100 < mouseX < 300100 < mouseY < 300 你会这样写:

这样做,您的代码将更改为:

  if (mouseIsPressed && mouseX > 100 && mouseX < 300 && mouseY > 100 && mouseY < 300 ) {
    // add a circle where the mouse is
    circles[circles.length] = { x: mouseX, y: mouseY, d: 30 };
  }

现在,当您在矩形外部单击时,不会添加任何圆圈。

请注意,由于圆圈以点击位置为中心,如果您点击离矩形边界太近的位置,您的圆圈(半径为 30/2=15)将被拉出矩形.

所以也许您更想要这样的条件:

  if (mouseIsPressed && mouseX > 100+15 && mouseX < 300-15 && mouseY > 100+15 && mouseY < 300-15 ) {

您可以看到它正在运行 here

此外,最好将所有这些度量(矩形位置、宽度和高度、圆直径)都放在变量中,这样您就不必对不同的值进行硬编码,但您会稍后当您的程序正常运行时可以这样做。