p5.js onclick重绘矩形

p5.js onclick redraw the rectangle

我想在点击时重绘圆圈内的矩形;任何人都可以提出一个想法吗?

function setup() {
createCanvas(700, 500);
  // Starts in the middle
  x = width / 2;
  y = height / 2;
}

function draw() {
    background(10);
    stroke(1000);
    fill(10);
    ellipse(x, y, 300, 300);

    rect(80, 80, 100, 50);
    rect(550, 180, 100, 50);
    rect(150, 400, 100, 50);
}

function mousePressed() {
    //question
}

remove() 清除整个 canvas。

我不确定你所说的“重新在圆圈内绘制矩形”是什么意思,而你最初根本没有绘制它,但我猜你只是意味着 "draw"。另外,不确定您是否希望所有这些仅在单击圆圈内时发生,但如果我的假设没问题,那么下面是解决方案。

它会在你点击的地方绘制矩形,前提是你点击的是圆圈内部。如您所见,我将所有代码从 draw() 移至 setup(),因为您并不真正需要它每秒刷新 30 次。如果这样做,则需要一个稍微不同的解决方案(下面的第二个)。

var myCircle;
var x, y, radius;
radius = 300;

function setup() {

    createCanvas(700, 500);
    // Starts in the middle
    x = width / 2;
    y = height / 2;

    background(10);
    stroke(255);
    fill(100);

    myCircle = ellipse(x, y, radius, radius);

    fill(50);
    rect(80, 80, 100, 50);
    rect(550, 180, 100, 50);
    rect(150, 400, 100, 50);

}

function draw() {
}

// global mousePressed handler - reacts on click anywhere on the PAGE (not just on canvas)
function mousePressed() {
    if (insideCircle()) {
        rect(mouseX-50, mouseY-25, 100, 50);
    }
    return false;
}

/**
* returns true if the mouse was clicked inside a circle (simply checks the distance of the click from the circle's center)
*/
function insideCircle() {
    return Math.sqrt(sq(mouseX-x) + sq(mouseY-y)) < radius/2 ? true : false;
}

不断重绘canvas的解决方案:

var x, y, radius;
radius = 300;

function setup() {
    createCanvas(700, 500);
    // Starts in the middle
    x = width / 2;
    y = height / 2;

}

function draw() {
    background(10);
    stroke(255);
    fill(100);    

    ellipse(x, y, radius, radius);

    fill(50);
    rect(80, 80, 100, 50);
    rect(550, 180, 100, 50);
    rect(150, 400, 100, 50);    
    if (mouseIsPressed) {
        if (insideCircle()) {
            rect(mouseX-50, mouseY-25, 100, 50);
        }
    }
}

// global mousePressed handler - reacts on click anywhere on the PAGE (not just on canvas)
function mousePressed() {
    // ignore it
}

/**
* returns true if the mouse was clicked inside a circle (simply checks the distance of the click from the circle's center)
*/
function insideCircle() {
    return Math.sqrt(sq(mouseX-x) + sq(mouseY-y)) < radius/2 ? true : false;
}