簡體   English   中英

如何在上一次點擊和最近一次點擊之間划一條線?

[英]How to draw a line between the previous click and the most recent click?

int previousX;
int previousY;
void  setup() {
   size(400, 400);
   stroke(255);
} 
void mousePressed(){
  previousX = mouseX;
  previousY = mouseY;
}
void  draw() {
   background(75, 55, 43);
   line(previousX,previousY,mouseX, mouseY);   
}

最終的結果應該是當用戶點擊鼠標時,從0,0到用戶點擊鼠標的地方會出現一條線,然后當用戶再次點擊鼠標時,會從上一次鼠標點擊到新的鼠標點擊。 示例:行(0,0,50,43)行(50,43,25,67)行(25,67,99,77)。 我目前沒有顯示任何永久行的代碼,但它具有先前的鼠標單擊。

最簡單的解決方案是不要用background(...)覆蓋前面的行。 它看起來像這樣:

int previousX;
int previousY;
void  setup() {
   size(400, 400);
   stroke(255);
} 
void mousePressed(){
  line(previousX,previousY,mouseX, mouseY);   
  previousX = mouseX;
  previousY = mouseY;
}
void  draw() {
}

請注意,僅當您不需要使用background(...)清除 canvas 時,它才會起作用。

為了繪制先前的永久線,您需要存儲所有先前的點。 這可以通過使用ArrayList來實現。 這些點是使用PVector存儲的,以對xy分量進行分組。

ArrayList<PVector> points = new ArrayList<PVector>(); 

void  setup() {
   size(400, 400);
   stroke(255);
   
   // The first point is (0, 0)
   points.add(new PVector(0, 0));
} 
void mousePressed(){
  // Each time the mouse is pressed add a new point
  points.add(new PVector(mouseX, mouseY));
}
void  draw() {
   background(75, 55, 43);
   
   // Loop through the array list
   for(int i = 0; i < points.size(); i++){
     if(i == points.size()-1){
       // For the last point draw a line to the mouse
       line(points.get(i).x, points.get(i).y, mouseX, mouseY);
     }else{
       // Draw a line between each of the points
       line(points.get(i).x, points.get(i).y, points.get(i+1).x, points.get(i+1).y);
     }
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM