JSFiddle - React, Tailwind, and code Playground

by Paras

HTML

<!--Create a canvas in HTML for our JS to work in.-->
<canvas id="myCanvas" width="640" height="480"></ canvas>

  <!--No need to type anything else in here.-->

CSS

/* Give the canvas a grey background. */

canvas {
  border: 1px solid black;
}


/* No need to type in here either! */

JavaScript

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");


var paddleX = 200;
var paddleY = 460;
var paddleWidth = 100;
var paddleHeight = 15;
var paddleDeltaX = 0;
var paddleDeltaY = 0;
var ballX = 300;
var ballY = 300;
var ballRadius = 10;
var bricksPerRow = 8;
var brickHeight = 20;
var brickWidth = canvas.width / bricksPerRow;
var score = 0;
var ballDeltaX;
var ballDeltaY;
var paddleDeltaX;
var paddleSpeedX = 10;
var gameLoop;
var paddleMove;

// Brick Layout: 1 is orange, 2 is green, 3 is gray, 0 means no brick 
var bricks = [
  [1, 1, 1, 1, 1, 1, 1, 2],
  [1, 1, 3, 1, 0, 1, 1, 1],
  [2, 1, 2, 1, 2, 1, 0, 1],
  [1, 2, 1, 1, 0, 3, 1, 1]
];




function drawPaddle() {
  context.fillRect(paddleX, paddleY, paddleWidth, paddleHeight);
}



function drawBall() {
  // Context.beginPath when you draw primitive shapes
  context.beginPath();

  // Draw arc at center ballX, ballY with radius ballRadius, 
  // From 0 to 2xPI radians (full circle)
  context.arc(ballX, ballY, ballRadius, 0, Math.PI * 2, true);

  // Fill up the path that you just drew
  context.fill();
}




// iterate through the bricks array and draw each brick using drawBrick()
function createBricks() {
  for (var i = 0; i < bricks.length; i++) {
    for (var j = 0; j < bricks[i].length; j++) {
      drawBrick(j, i, bricks[i][j]);
    }
  }
}

// draw a single brick
function drawBrick(x, y, type) {
  switch (type) { // if brick is still visible; three colors for three types of bricks
    case 1:
      context.fillStyle = 'orange';
      break;
    case 2:
      context.fillStyle = 'rgb(100,200,100)';
      break;
    case 3:
      context.fillStyle = 'rgba(50,100,50,.5)';
      break;
    default:
      context.clearRect(x * brickWidth, y * brickHeight, brickWidth, brickHeight);
      break;

  }
  if (type) {
    //Draw rectangle with fillStyle color selected earlier
    context.fillRect(x * brickWidth, y * brickHeight, brickWidth, brickHeight);
    // Also draw blackish...