Store the start and end position of a mousedrag?

edited November 2017 in How To...

As the topic suggests, is there any way to get the start and end position of a single mouse drag?


  • Answer ✓

    In the Processing's website under reference, you can check the following key words: mousePressed() and mouseReleased(). Sample code below.

    PVector mStart;
    PVector mEnd;
    void setup(){}
    void draw(){println(if(mStart!=null) mStart.dist(mEnd))}
    void mousePressed(){mStart=new PVector(mouseX,mouseY);}
    void mouseReleased(){mEnd=new PVector(mouseX,mouseY);}


  • edited November 2017 Answer ✓
    boolean mouseWasDown;
    float startEnd[] = new float[4];

    Start position:

    • on mousePressed
      • if mouseWasDown == false;
        • startEnd[0] = mouseX;
        • startEnd[1] = mouseY
        • mouseWasDown = true;

    End position:

    • on mouseReleased
      • startEnd[2] = mouseX;
      • startEnd[3] = mouseY;
      • mouseWasDown = false;

    Show it:

    line( startEnd[0], startEnd[1], startEnd[2], startEnd[3] );
  • edited December 2017

    Here is a more advanced example using the built-in mouseDragged -- it also saves a collection of previously drawn lines as children of a PShape, then displays the collection of past lines in the draw loop.

    If you wanted specifying lines to be based on a two-point clicking rather than dragging, you would need a state variable like an int to track which state you were in -- click the first point, click the second, or click again to save / clear, then click the first point....

    PVector mStart;
    PVector mEnd;
    boolean wasDown;
    PShape lines;
    void setup() {
      mStart = new PVector(0, 0);
      mEnd = new PVector(0, 0);
      lines = createShape();
    void draw() {
      // saved lines
      for(int i=0; i<lines.getChildCount(); i++){
      // preview line
      line(mStart.x, mStart.y, mEnd.x, mEnd.y);
    void mousePressed() {
      // start preview line
      mStart.set(mouseX, mouseY);
      mEnd.set(mouseX, mouseY);
    void mouseDragged() {
      // update preview line
      mEnd.set(mouseX, mouseY);
    void mouseReleased() {
      // create a line shape
      PShape newline = createShape();
      newline.vertex(mStart.x, mStart.y);  
      newline.vertex(mEnd.x, mEnd.y);  
      // save it
      // reset preview line
      mStart.set(-10, -10);
      mEnd.set(-10, -10);


Sign In or Register to comment.