p5.j​​s onclick重绘矩形

时间:2015-04-10 16:54:10

标签: p5.js

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

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()擦除整个画布。

1 个答案:

答案 0 :(得分:0)

我不确定你的意思是“重新在圆圈内绘制矩形”,当你最初没有绘制它时,但我猜你只是意味着“画” 。此外,不确定您是否希望所有这些只发生在圈内点击,但如果我的假设是正确的,那么下面是解决方案。

如果您在圆圈内单击,它将在您单击的位置绘制矩形。正如您所看到的,我将所有代码从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;
}

不断重绘画布的解决方案:

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