JSFiddle - React, Tailwind, and code Playground

HTML

<canvas id="tutorial" width="600" height="600"></canvas>

JavaScript

let coords = [];
coords = [
  {x: 0, y: 0},
  {x: 0, y: 600},
  {x: 600, y: 600},
  {x: 600, y: 0}]

const canvas = document.getElementById('tutorial');
const ctx = canvas.getContext('2d');

canvas.addEventListener('click', createBox)
canvas.addEventListener('mousemove', radar)

function drawLine(pointA, pointB, color) {
  ctx.beginPath();
  ctx.moveTo(pointA.x, pointA.y);
  ctx.lineTo(pointB.x, pointB.y);
  ctx.strokeStyle = color;
  ctx.stroke();
}

function distance(pointA, pointB) {
  return Math.sqrt(Math.pow((pointA.x - pointB.x), 2) + Math.pow((pointA.y - pointB.y), 2))
}

function getClosestPoint(points, givenPoint) {
  let min = {point: points[0], dist: distance(points[0], givenPoint)};
  for (let point of points) {
    if (distance(point, givenPoint) < min.dist) {
       min = {point: point, dist: distance(point, givenPoint)}
    }
  }
  return min.point;
}

function radar(event) {
  const userPoint = {x: event.clientX, y: event.clientY};
  const closest = getClosestPoint(coords, userPoint);
  drawLine(closest, userPoint, 'green')
  setInterval(function() { 
   ctx.clearRect(0, 0, canvas.width, canvas.height)
  }, 3000);
}

function createBox(event) {
  const userPoint = {x: event.clientX, y: event.clientY};
  const closest = getClosestPoint(coords, userPoint);
  canvas.removeEventListener('mousemove', radar)
  drawLine(closest, userPoint, 'red');
}