'How do I implement the animation of a line draw in p5js?

If I change the percentage variable to 0.5 it draws a small line at the midpoint so I assume that only calls the function once. I have tried putting a while loop around this block.

while(percentage < 0.99){
  var mid = start.lerp(end, percentage);
  line(start.x, start.y, mid.x, mid.y);
  percentage += 0.00001;
}

But it seems to wait to break out of the while loop and then draw the entire line.

Heres the rest of the code structure.

function draw(){
  a();
}
function a(){
  //do some math and calculate points
  animate_line(x, y, x2, y2);
}

var start;
var end;
var percentage = 0;

function animate_line(x, y, x2, y2){
  start = createVector(x, y);
  end = createVector(x2, y2);
  
  
  var mid = start.lerp(end, percentage);
  line(start.x, start.y, mid.x, mid.y);
  percentage += 0.00001;
}


Solution 1:[1]

Is that the entire code? Looks like you are missing a background (among a few other elements to make this functional).

function draw(){
  background(20)
  stroke(200)
  a();
}

But I think the main problem here is that you are drawing a line from the starting point to the same point. When you do mid = start.lerp(end, percentage); you are modifying start and then also making mid equal to start. Try using static version p5.Vector.lerp() like this:

mid = p5.Vector.lerp(start,end,percentage)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zJorge