Canvas code cleanup for Rogue-like

I never completed the Rogue-like for the old front end certificate and it’s been driving me crazy. So I started fresh and so far have this random walker, using Canvas.

What’s bothering me is the javascript doesn’t seem very clean. to use canvas I’m calling a function when the body loads, so then all of my code is within that draw() function.

I want to create multiple “diggers” at a time, so would need to create a Digger (or Walker) object, right?

I have tried to create a new class, but it’s inside this draw () function and so it’s not working well.

My question is how to I create a Walker / Digger class so I can run multiple Diggers at once that will interact with each other’s edges adn boundaries, while using Canvas?

Code Here, codepen link below to view in acction


function draw() {
  const ctx = document.getElementById('canvas').getContext('2d');
  const { width, height } = canvas.getBoundingClientRect();
      const startX = width /2
      const startY = height/2
      let x  = startX
      let y = startY
      const tiles = 50000
      const size = 5
      
      let timeout
      let timer_on = false

    
    
    function display()  {
      ctx.fillStyle = `rgb(0,0,0)`;
      ctx.fillRect(x,y,size,size);
    }
  
    function step() {
      let choice = Math.floor(Math.random()*4)
      console.log(choice)
        if (choice == 0) {
         ( x < width-size ? x+=size : x=startX)
      } else if (choice == 1) {
         ( x > size ? x-=size : x=startX )
      } else if (choice == 2) {
         ( y<height-size ? y+=size : y=startY)
      } else {
         ( y>size ? y-=size : y==startY)
      }
    }
 

 function startDigging() {
      if (!timer_on) {
        timer_on = true;
        walk()
      }
    
    }
 draw.startDigging = startDigging;
  
  function stopDigging() {
      clearTimeout(timeout)
      timer_on = false
    }
  
  draw.stopDigging=stopDigging;
  
  function walk() {
      display(x,y)
      step(x,y)
      timeout = setTimeout(walk, 0)
  }
  
  
  // for (let i=0; i<tiles; i++) {
  //     setTimeout(function() {              // Invoke the callback the first time 
  //         walk();              // after first 1 seconds.
  //     }, 1000);
  // }

}