JSFiddle - React, Tailwind, and code Playground

by Kelvin Russell

HTML

<canvas id="c" width="200" height="200"></canvas>
<canvas id="d" width="200" height="200"></canvas>
<canvas id="s" width="360" height="200"></canvas>

CSS

canvas {
  border: 2px solid #000;
  position:absolute;
  top: 10px;
  left: 10px;
}
canvas#s {
  top: 240px;
}

JavaScript

var ctx = c.getContext("2d");
var dtx = d.getContext("2d");
var stx = s.getContext("2d");
var cos = Math.cos;
var sin = Math.sin;
var r = 120;
var a = (Math.PI / 180) * 0;
var x;
var y;
var rs = -((Math.PI / 180) * 30);
var re = (Math.PI / 180) * 30;
var degree = (Math.PI / 180);
var i;
var direction = 0;
var position = {"x":100,"y":100};
// generate a map
for(i=0;i<15;i++) {
  //dtx.fillStyle = 'rgba('+gri(0,255)+',0,0,255)';
  dtx.fillRect(gri(0,200),gri(0,200), gri(2,50),gri(2,50));
}
var map = dtx.getImageData(0,0,200,200);

draw();

function getMapXY (x,y) {
	var d = map;
  ctx.fillRect(x,y,1,1);
	xx = 4 * (x + (y * 200));
  val = d.data[xx+3];
  return (val==255);
}

function draw() {
ctx.clearRect(0,0,200,200);
stx.fillStyle = "blue";
stx.fillRect(0,0,360,100);
stx.fillStyle = "grey";
stx.fillRect(0,100,360,100);
stx.fillStyle = "black";
//direction += 0.02;
  sx = 0;
  
  for (i = rs; i < re; i += degree) {
		
    var wall = checkRayCollision(i + direction, position.x, position.y, r);
    x = (r - wall) * cos(i + direction) + 100;
    y = (r - wall) * sin(i + direction) + 100;

    if(wall > 0)
        wall = r - wall;
		stx.fillRect(sx, 100 - (wall/2), 6, wall);
    sx+=6;
  }
  window.requestAnimationFrame(draw);
}

function checkRayCollision(theta, originx, originy, length) {
  var k;
  for (k = 0; k < length; k+=2) {
    x = k * cos(theta) + originx;
    y = k * sin(theta) + originy;
		if( getMapXY(Math.floor(x),Math.floor(y)) ) {
    	return k;
    }
  }
  return 0;
}

function gri(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

document.addEventListener("keydown", (a)=>{
//console.log(a)
	switch (a.key){
  case "w": position.y -= 2
  break;
  case "s": position.y += 2
  break;
  case "a": position.x -= 2
  break;
  case "d": position.x += 2
  break;
  case "ArrowLeft": direction -= 0.05;
  break;
  case "ArrowRight": direction += 0.05;
  break;
  }
});