Search code examples
javascriptprocessingp5.js

How would I create dots in-between 2 positions on a canvas for P5.js?


So ultimately I'm trying to figure out a loop that could create dots in-between the 2 points. If anyone could figure this out it would be greatly appreciated!

let pos1 = {x:383,y:202};
let pos2 = {x:754,y:387};

let dotRadius = 5;

let divisions = 10; 

// Try to create 'divisions' amount of dots between pos1 and pos2

function setup() {
  createCanvas(768,768);
  
}

function draw() {
  background(50,50,50);
  rectMode(CENTER);
  
  stroke(180,180,180);
  
  circle(pos1.x, pos1.y,dotRadius);
  circle(pos2.x, pos2.y,dotRadius);
  
  noLoop();
}

Solution

  • You can use a for loop and conditionals to draw the circles incrementing the x and y values in each iteration.

    let pos1 = {x:383,y:202};
    let pos2 = {x:754,y:387};
    
    let dotRadius = 5;
    
    let divisions = 10;
    
    // Try to create 'divisions' amount of dots between pos1 and pos2
    
    let increment_x = (pos2.x-pos1.x)/(divisions+1)
    let increment_y = (pos2.y-pos1.y)/(divisions+1)
    
    
    function setup() {
      createCanvas(768,768);
      
    }
    
    function draw() {
      background(50,50,50);
      rectMode(CENTER);
      
      stroke(180,180,180);
      
      circle(pos1.x, pos1.y,dotRadius);
      circle(pos2.x, pos2.y,dotRadius);
    
      let y=pos1.y
      
      for (let x=pos1.x; x<pos2.x; x+=increment_x) {
        if (y<pos2.y){
          circle(x, y,dotRadius);
        }
        y+=increment_y
      }
    }