Grid ray tracing

by Mr Pingouin

HTML

<canvas id="myCanvas" width="500" height="500"></canvas>

<div class="optionContainer">
  <input type="range" min="1" max="50" value="10" class="slider" id="scaleRange">
</div>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var SIZE = 500;

function Point(px, py) {
  this.x = px;
  this.y = py;
}

function drawGrid(gridSize, color) {
  ctx.fillStyle = color;
  for (var i = 0; i < SIZE; i += gridSize) {
    ctx.fillRect(0, i, SIZE, 1);
    ctx.fillRect(i, 0, 1, SIZE);
  }
}

function drawPoint(p, color) {
  ctx.strokeStyle = color;
  ctx.beginPath();
  ctx.arc(p.x, p.y, 5, 0, 2 * Math.PI);
  ctx.stroke();
}

function drawDirectLine(p1, p2, color, k) {
  ctx.strokeStyle = "#000000";
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p1.x + (p2.x - p1.x) * k, p1.y + (p2.y - p1.y) * k);
  ctx.stroke();
}


function drawSquare(p, scale) {
  ctx.fillStyle = "#0000FF";
  ctx.fillRect(p.x - p.x % scale, p.y - p.y % scale, scale, scale);
}


function drawRay(p1, p2, scale, iters) {

  var a = p1.y - p2.y;
  var b = p2.x - p1.x;
  var c = p1.y * p2.x - p1.x * p2.y;

  var stepX = p1.x < p2.x ? 1 : -1;
  var stepY = p1.y < p2.y ? 1 : -1;

  stepX *= scale;
  stepY *= scale;

  var deltaX = Math.abs(a * scale / b);
  var deltaY = scale;


  var bnx = p1.x - (p1.x % scale) + scale;


  if (stepX < 0) {
    bnx = p1.x - (p1.x % scale);
  }

  var tMaxX = Math.abs((((c - a * bnx) / b) - p1.y));


  var tMaxY = scale - p1.y % scale;

  if (stepY < 0) {
    tMaxY = p1.y % scale;
  }

  var currentPoint = {
    x: p1.x,
    y: p1.y
  };
  drawSquare(currentPoint, scale);
  for (var i = 0; i < iters; i++) {
    if (tMaxX <= tMaxY) {
      tMaxX += deltaX;
      currentPoint.x += stepX;
    } else {
      tMaxY += deltaY;
      currentPoint.y += stepY;
    }
    drawSquare(currentPoint, scale);
  }
}


function drawScene(p1, p2, scale) {


  ctx.clearRect(0, 0, SIZE, SIZE);

  drawGrid(scale, "#DDDDDD");

  drawRay(p1, p2, scale, (SIZE * 2) / scale);

  drawPoint(p1, "#00FF00");
  drawPoint(p2, "#FF0000");
  drawDirectLine(p1, p2, "#000000", 100);

}

var pointA = new Point(215, 100);
var pointB = new Point(155, 155);
var SCALE = 5;
var t =...