A* Algorithm

An implementation of the A* algorithm to work out a path between 2 points in a canvas.

by sperske

HTML

<script src="https://cdn.jsdelivr.net/npm/javascript-astar/astar.js"></script>
<code>Click on any 2 points on white spaces and a path will be drawn</code>
<canvas id='field' height='200' width='320'></canvas>
<textarea id='Graph' wrap='off'></textarea>

CSS

#field {
  border: thin black solid;
  width: 98%;
  background: #FFFFC7;
}

#Graph {
  width: 98%;
  height: 300px;
}

JavaScript

var img,
  field = document.getElementById('field'),
  EngineBuilder = function(field, size) {
    var context = field.getContext("2d"),
      graphSettings = {
        size: size,
        mid: Math.ceil(size / 2)
      },
      engine = {
        getPosition: function(event) {
          var bounds = field.getBoundingClientRect(),
            x = Math.floor(((event.clientX - bounds.left) / field.clientWidth) * field.width),
            y = Math.floor(((event.clientY - bounds.top) / field.clientHeight) * field.height),
            node = graph.grid[Math.floor(y / graphSettings.size)][Math.floor(x / graphSettings.size)];

          return {
            x: x,
            y: y,
            node: node
          }
        },
        drawObstructions: function() {
          context.clearRect(0, 0, 320, 200);
          if (img) {
            context.drawImage(img, 0, 0);
          } else {
            context.fillStyle = 'rgb(0, 0, 0)';
            context.fillRect(200, 100, 50, 50);
            context.fillRect(0, 100, 50, 50);
            context.fillRect(100, 100, 50, 50);
            context.fillRect(0, 50, 150, 50);
          }
        },
        simplifyPath: function(start, complexPath, end) {
          var previous = complexPath[1],
            simplePath = [start, {
              x: (previous.y * graphSettings.size) + graphSettings.mid,
              y: (previous.x * graphSettings.size) + graphSettings.mid
            }],
            i, classification, previousClassification;
          for (i = 1; i < (complexPath.length - 1); i++) {
            classification = (complexPath[i].x - previous.x).toString() + ':' + (complexPath[i].y - previous.y).toString();

            if (classification !== previousClassification) {
              simplePath.push({
                x: (complexPath[i].y * graphSettings.size) + graphSettings.mid,
                y: (complexPath[i].x * graphSettings.size) + graphSettings.mid
              });
            } else {
             ...