Search code examples
javascriptprocessingdrawingdrawp5.js

Creating a Square by lines and through user input in p5.js


I am learning user input through mouse in p5.js and i want to create a square by 4 line method on 4 different clicks , 1 click for each line and the last click completing the square. below code is for 2 lines but the are both running at the same time and i cannot understand the if command to separately run them .

function setup() {
    createCanvas(400, 400);
    background(220);
}

function draw() {  
}

function mousePressed()
{
    line(width/20,height/40,mouseX,mouseY);
    line(pmouseX,pmouseY,mouseX,mouseY);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


Solution

  • You've to store the points to a list. If the list contains 4 elements and the mouse is clicked again, clear the list:

    var pts = [];
    function mousePressed()
    {
        if (pts.length == 4) {
            pts = [];
        }
        pts.push([mouseX, mouseY])
    }
    

    Do all the drawing continuously in draw(). Clear the background. Draw the liens between the points ins a loop. If the number of point is 4, the draw a line from the last point to the 1st point.
    Additionally you can draw a "rubber" line from the last point to the current mouse position, if there is at least 1 point in the list:

    function draw() {  
          background(220);
    
          // draw the lines between the points
          for (var i=0; i < pts.length-1; ++i) {
              line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]);
          }
    
          var close = pts.length == 4;
          if (close) {
              // draw line from 1st point to at point
              line(pts[pts.length-1][0], pts[pts.length-1][1], pts[0][0], pts[0][1]); 
          }
          else if (pts.length > 0) {
              // draw a rubber line from last point to the mouse
              line(pts[pts.length-1][0], pts[pts.length-1][1], mouseX,mouseY); 
          }
    }
    

    See the example

    function setup() {
      createCanvas(400, 400);
    }
    
    var pts = [];
    function mousePressed()
    {
        if (pts.length == 4) {
            pts = [];
        }
        pts.push([mouseX, mouseY])
    }
    
    function draw() {  
          background(220);
    
          // draw the lines between the points
          for (var i=0; i < pts.length-1; ++i) {
              line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]);
          }
    
          var close = pts.length == 4;
          if (close) {
              // draw line from 1st point to at point
              line(pts[pts.length-1][0], pts[pts.length-1][1], pts[0][0], pts[0][1]); 
          }
          else if (pts.length > 0) {
              // draw a rubber line from last point to the mouse
              line(pts[pts.length-1][0], pts[pts.length-1][1], mouseX,mouseY); 
          }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>