JSFiddle - React, Tailwind, and code Playground
by alexdickson
HTML
<canvas id="pong">
</canvas>
CSS
canvas {
width: 400px;
height: 400px;
background: #000;
}
JavaScript
(function() {
var canvas = document.getElementById('pong'),
canvasWidth = canvas.width,
canvasHeight = canvas.height,
ctx = canvas.getContext('2d');
var player;
document.onkeydown = function(event) {
switch (event.keyCode) {
// Up arrow
case 38:
player.moveUp();
break;
// Down arrow
case 40:
player.moveDown();
break;
}
};
var Paddle = function(x, y, color) {
this.x = x;
this.prevX
this.y = y;
this.prevY;
this.width = 10;
this.height = 20;
this.color = color;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.clearRect(this.prevX, this.prevY, this.width, this.height);
ctx.fillRect(this.x, this.y, this.width, this.height);
this.prevX = this.x;
this.prevY = this.y;
}
this.moveDown = function() {
this.y += 10;
this.draw();
}
this.moveUp = function() {
this.y -= 10;
this.draw();
}
}
var Ball = function(x, y, color) {
this.x = x;
this.prevX
this.y = y;
this.prevY;
this.radius = 10;
this.color = color;
this.bounceInterval;
this.draw = function() {
ctx.clearRect(this.prevX - this.radius, this.prevY - this.radius, this.radius * 2, this.radius * 2);
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.fill();
this.prevX = this.x;
this.prevY = this.y;
}
this.bounce = function() {
var that = this;
this.bounceInterval = setInterval(function() {
that.x += 10;
that.draw();
}, 1000);
}
this.freeze = function() {
...