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

Time:03-18

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();
}

CodePudding user response:

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
  }
}

CodePudding user response:

The primary way to calculate the dots between two points is getting the x-difference and the y-difference.

let my = pos2.y - pos1.y;
let mx = pos2.x - pos1.x;

Then each x- and y-coordinate can be calculated between based on starting positions, ending positions, and the number of divisions.

Full code (see the running example on the p5.js Editor):

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 drawDivisions() {
  // Get the y-distance
  let my = pos2.y - pos1.y;

  // Get the x-distance
  let mx = pos2.x - pos1.x;

  // Add 1 to divisions so that it creates 'divisions' points between, not including start nor end
  let div = divisions   1;

  // get the step value for y
  let dy = my / div;

  // get the step value for x
  let dx = mx / div;

  // Set a different color just to set these new dots apart
  stroke(240, 40, 180);

  // Enter the loop and create 'divisions' points
  for (let i = 1; i <= divisions; i  ) {
    let x = pos1.x   dx * i;
    let y = pos1.y   dy * i;
    circle(x, y, dotRadius);
  }
}

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);

  // Enter our function to draw dots between start and end
  drawDivisions();

  noLoop();
}
  • Related