JSFiddle - React, Tailwind, and code Playground

by carsont

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/ocanvas/2.8.3/ocanvas.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<body>
  <canvas id="canvas"></canvas>
</body>

CSS

canvas {
  border: 1px solid black;
}

JavaScript

(function() {
  var requestAnimationFrame =
    window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
width = 500,
  height = 200,
  player = {
    x: width / 2,
    y: height - 15,
    width: 5,
    height: 5,
    speed: 3,
    velX: 0,
    velY: 0,
    jumping: false,
    grounded: false
  },
  keys = [],
  friction = 0.8,
  gravity = 0.3;

var boxes = [];

// dimensions
boxes.push({
  x: 0,
  y: 0,
  width: 10,
  height: height
});
boxes.push({
  x: 0,
  y: height - 2,
  width: width,
  height: 50
});
boxes.push({
  x: width - 10,
  y: 0,
  width: 50,
  height: height
});

boxes.push({
  x: 120,
  y: 10,
  width: 80,
  height: 80
});
boxes.push({
  x: 170,
  y: 50,
  width: 80,
  height: 80
});
boxes.push({
  x: 220,
  y: 100,
  width: 80,
  height: 80
});
boxes.push({
  x: 270,
  y: 150,
  width: 40,
  height: 40
});

canvas.width = width;
canvas.height = height;

function update() {
  // check keys
  if (keys[38] || keys[32]) {
    // up arrow or space
    if (!player.jumping && player.grounded) {
      player.jumping = true;
      player.grounded = false;
      player.velY = -player.speed * 2;
    }
  }
  if (keys[39]) {
    // right arrow
    if (player.velX < player.speed) {
      player.velX++;
    }
  }
  if (keys[37]) {
    // left arrow
    if (player.velX > -player.speed) {
      player.velX--;
    }
  }

  player.velX *= friction;
  player.velY += gravity;

  ctx.clearRect(0, 0, width, height);
  ctx.fillStyle = "black";
  ctx.beginPath();

  player.grounded = false;
  for (var i = 0; i < boxes.length; i++) {
    ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);

    var dir = colCheck(player, boxes[i]);

    if (dir === "l" || dir === "r") {
      player.velX = 0;
      player.jumping = false;
 ...