JSFiddle - React, Tailwind, and code Playground

by Blummer92

HTML

<canvas id="myCanvas" width="480" height="320">

CSS

* {
  padding: 0;
  margin: 0;
}
canvas {
  background: #eee;
  display: block;
  margin: 0 auto;
  z-index: 0;
  }

JavaScript

//this sets the canvas area
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

//every frame has been drawn to make it appear that the ball is moving
//this sets the moving ball
let circleX = canvas.width / 2;
let circleY = canvas.height - 30;
var ballRadius = 10;

// newly spawned objects start at Y=25
var spawnLineY = 25;

// spawn a new object every 1500ms
var spawnRate = 1500;

// set how fast the objects will fall
var spawnRateOfDescent = 0.5;

// when was the last object spawned
var lastSpawn = -1;

// this array holds all spawned object
var objects = [];

// save the starting time (used to calc elapsed time)
var startTime = Date.now();

var dx =2;
var dy =-2;
//paddle
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

//When the keydown event is fired on any of the keys on your keyboard (when they are pressed),
function keyDownHandler(e) {
  if (e.key == "Right" || e.key == "ArrowRight") {
    rightPressed = true;
  } else if (e.key == "Left" || e.key == "ArrowLeft") {
    leftPressed = true;
  }
}
function keyUpHandler(e) {
  if (e.key == "Right" || e.key == "ArrowRight") {
    rightPressed = false;
  } else if (e.key == "Left" || e.key == "ArrowLeft") {
    leftPressed = false;
  }
}
function spawnRandomObject(object) {

    // select a random type for this new object
    var t;

    // About Math.random()
    // Math.random() generates a semi-random number
    // between 0-1. So to randomly decide if the next object
    // will be A or B, we say if the random# is 0-.49 we
    // create A and if the random# is .50-1.00 we create B

    if (Math.random() < 0.50) {
        t = "red";
    } else {
        t = "blue";
    }

    // create the new object
    var object = {
        // set this objects type
      ...