繁体   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