Create path from image shape outline


Hi there,

I’m working on a project to create toolpaths for a “zen” coffeetable.
The goal is to create a pattern, and to be able to follow shapes in an image (black on white image, e.g. logo’s).
So far i’m able to create the pattern i want, and was able to detect the edges of a shape.
But when it comes to making a path around that shape, i’m struggling.
The idea is that there is a start point from where the path will start. It should then check all points of the edges and look for the closest point and add it to the path. And loop this until we’re back at the start point.

So far i’m able to loop trough a few points, but it seems to get stuck or something, and seems to use the same point more then once, even though i have a check for this, and after hours of trial and error, here i am.
Below is the part of the code responsible for following the shape.
Full sketch can be found here:
(the code below can be found in the function followShapePath)
Hopefully someone smarter than me can help out with this, if anything was unclear feel free to ask.

let points = 0;
  for(let c = 0; c < 500; c++)//Number of points in path
    let distance_02 = 100000;
    let closestPoint_02 = 100000;
    let closestX = 100000;
    let closestY = 100000;
    let prevDistance = 0;
    let gpX = generatedPathX[gpIndex-1];//last point in the path
    let gpY = generatedPathY[gpIndex-1];//last point in the path
    for(let a = 0; a < scIndex-1; a++)//looping trough the shape edge points
      let curX = shapesContourX[a];
      let curY = shapesContourY[a];
      let curDistance = dist(gpX, gpY, curX, curY);
      if(curDistance < distance_02 && curDistance > 0)//is the distance smaller than the current smallest distance & bigger than zero?
        for(let b = 0; b < scuIndex-1; b++)//checks if location is used
          let usedX = shapesContourXused[b];
          let usedY = shapesContourYused[b];
          if(usedX != curX && usedY != curY)//does point exist in path already?
           distance_02 = curDistance;
           closestPoint_02 = a;   //unused at this point
           closestX = curX;
           closestY = curY;
    points += 1;
    shapesContourXused[scuIndex] = closestX;
    shapesContourYused[scuIndex] = closestY;
    scuIndex += 1;

    generatedPathX[gpIndex] = closestX;
    generatedPathY[gpIndex] = closestY;
    gpIndex += 1;