Not drawing at desired position in “Processing”

2019-07-26 08:08发布

问题:

I am trying to draw at one place by dragging a mouse (for example, a circle in left upper quadrant) and have the figure appear at 4 places around center of canvas (including one right under the mouse cursor). I have tried following code:

int x=0;
int y=0;

void setup(){
   size(400, 400);  
   background(255); 
   translate(width/2, height/2); 
}
void draw() {
}

void mouseDragged(){
    translate(width/2, height/2); 

    for(int i=0; i<4; i++){
      rotate(PI/2); 
      x= mouseX ; y=mouseY;
      line(x, y, mouseX, mouseY);
    }
  }

However, the figure does not get drawn under the mouse cursor. If I am very close to upper left corner, the lines get drawn at center of canvas.

Secondly, a total of 5 figures get drawn instead of 4 as I am trying. If I draw near left upper corner, the unwanted figure appears at right lower corner of canvas. This unwanted figure is fainter than other figures.

Where are the errors and how can both these problems be corrected? I want to achieve this with rotate commands (rotating around center of canvas), though I saw that I can also use translate command to draw at 4 places on canvas.

Thanks for your help.

回答1:

None of your points are under the mouse because you're translating the canvas (to width/2, height/2) before drawing your points, but you're using mouseX, mouseY to draw them. Think of mouseX, mouseY as the X and Y distance from the upper-left corner. If you want a point to be under the mouse, you have to use the distance from the point you translated to!

In other words, instead of this:

x = mouseX; 
y = mouseY;

You want this:

x = width/2 - mouseX; 
y = height/2 - mouseY;

As for the extra point being drawn, that seems to be a side-effect of using the mouseDragged() function. Something strange is going on there, but you can get around this problem by just using the draw() function and the mousePressed variable instead of the mouseDragged() function.

Edit: I switched the order they should be in. Check out my answer to your next question for a better explanation.