JSFiddle - React, Tailwind, and code Playground

by Laxmikant Dange

HTML

<canvas id="can"></canvas>

CSS

canvas {
  border: 1px solid #F00;
}

JavaScript

var can = document.getElementById('can');
var ctx = can.getContext('2d');

can.width = 500
can.height = 500

environment();
const totalForce = 100
drawDirections({
  x: 250,
  y: 465,
  angle: (27 + 180) * (Math.PI / 180)
}, totalForce);
ctx.stroke();

const staticBodies =[];

function drawDirections(position, force) {
  position.x = position.x + Math.sin(position.angle) * 5;
  position.y = position.y + Math.cos(position.angle) * 5;
  ctx.moveTo(position.x, position.y);
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(position.x, position.y, 5, 0, Math.PI * 2);
  ctx.closePath();
  const f = parseInt((force / totalForce) * 100) / 100;
  console.log(f)
  ctx.fillStyle = 'rgba(0,0,0,' + f + ')';
  ctx.strokeStyle = 'rgba(0,0,0,0)'
  ctx.fill();
  if (force <= 0 || inPocket(position)) {
    return
  }
  drawDirections(position, force - 0.5);
}

function inPocket(position, force) {
  return (position.x < 25 && position.y < 25) ||
    (position.x < 25 && position.y > 475) ||
    (position.x > 475 && position.y < 25) ||
    (position.x > 475 && position.y > 475)
}

function drawPlayLines(fromX, fromY, toX, toY, direction) {
  ctx.moveTo(fromX, fromY);
  ctx.lineTo(toX, toY);
  ctx.moveTo(fromX + (!direction * 15), fromY + (direction * 15));
  ctx.lineTo(toX + (!direction * 15), toY + (direction * 15));
}

function detectCollision(){
	
}

function environment() {
  //	Top Left
  ctx.arc(10, 10, 20, 0, 2 * Math.PI);

  //	Top Right
  ctx.moveTo(500, 0);
  ctx.arc(490, 10, 20, 0, 2 * Math.PI);

  //	Bottom Left
  ctx.moveTo(30, 490);
  ctx.arc(10, 490, 20, 0, 2 * Math.PI);

  //	Bottom Right 
  ctx.moveTo(500, 500);
  ctx.arc(490, 490, 20, 0, 2 * Math.PI);

  //	Top
  drawPlayLines(50, 30, 450, 30, true);

  //	Bottom
  drawPlayLines(50, 455, 450, 455, true);

  //	Left
  drawPlayLines(455, 50, 455, 450, false);

  //	Right
  drawPlayLines(30, 50, 30, 450, false);
}