JSFiddle - React, Tailwind, and code Playground
by Ben Centra
HTML
<canvas id="canvas" width="600" height="400" tabindex="1"></canvas>
CSS
#canvas {
width: 600px;
height: 400px;
border: 1px solid black;
}
JavaScript
// Canvas Pong
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// Key Codes
var W = 87;
var S = 83;
var UP = 38;
var DOWN = 40;
// Keep track of pressed keys
var keys = {
W: false,
S: false,
UP: false,
DOWN: false
};
// Create a rectangle object - for paddles, ball, etc
function makeRect(x, y, width, height, speed, color) {
if (!color) color = '#000000';
return {
x: x,
y: y,
w: width,
h: height,
s: speed,
c: color,
draw: function() {
context.fillStyle = this.c;
context.fillRect(this.x, this.y, this.w, this.h);
}
};
}
// Create the paddles
var paddleWidth = 25;
var paddleHeight = 100;
var leftPaddle = makeRect(25, canvas.height / 2 - paddleHeight / 2, paddleWidth, paddleHeight, 5, '#BC0000');
var rightPaddle = makeRect(canvas.width - paddleWidth - 25, canvas.height / 2 - paddleHeight / 2, paddleWidth, paddleHeight, 5, '#0000BC');
// Keep track of the score
var leftScore = 0;
var rightScore = 0;
// Create the ball
var ballLength = 15;
var ballSpeed = 2;
var ball = makeRect(0, 0, ballLength, ballLength, ballSpeed, '#000000');
// Modify the ball object to have two speed properties, one for X and one for Y
ball.sX = ballSpeed;
ball.sY = ballSpeed / 2;
// Randomize initial direction
if (Math.random() > 0.5) {
ball.sX *= -1;
}
// Randomize initial direction
if (Math.random() > 0.5) {
ball.sY *= -1;
}
// Reset the ball's position and speed after scoring
function resetBall() {
ball.x = canvas.width / 2 - ball.w / 2;
ball.y = canvas.height / 2 - ball.w / 2;
ball.sX = ballSpeed;
ball.sY = ballSpeed / 2;
}
// Bounce the ball off of a paddle
function bounceBall() {
// Increase and reverse the X speed
if (ball.sX > 0) {
ball.sX += 1;
// Add some "spin"
if (keys.UP) {
ball.sY -= 1;
} else if (keys.DOWN) {
ball.sY += 1;
}
} else {
ball.sX -= 1;
// Add some "spin"
if (keys.W) {
ball.sY -= 1;
} else if...