JSFiddle - React, Tailwind, and code Playground
HTML
<section id="pong" class="c-section">
<div class="c-section__pong js-pong"></div>
<div class="c-section__inner">
<p class="c-section__paragraph">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut, pariatur. Molestias facilis sed hic at, perspiciatis et pariatur ab blanditiis ea, tenetur est expedita nihil illo beatae ex repellendus quasi. Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Aut ipsum quasi natus error nam incidunt ex et at aliquam illo rerum nemo quaerat, quae nobis, officiis veniam temporibus iusto, laudantium?
</p>
</div>
</section>
SCSS
.c-section {
z-index: 99999;
background: green;
opacity: 0.5;
&__inner {
margin: 100px;
.c-section__paragraph {
padding: 100px 0;
}
}
&__pong {
position: relative;
z-index: -1;
canvas {
display: block;
position: absolute;
}
}
}
JavaScript
var animate = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
window.setTimeout(callback, 1000 / 60)
};
var canvas = document.createElement("canvas");
var width = document.getElementById('pong').offsetWidth;
var height = document.getElementById('pong').offsetHeight;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
var player = new Player();
var computer = new Computer();
var ball = new Ball(width / 2, height / 2);
var keysDown = {};
var render = function() {
context.fillStyle = "red";
context.fillRect(0, 0, width, height);
player.render();
computer.render();
ball.render();
};
var update = function() {
player.update();
computer.update(ball);
ball.update(player.paddle, computer.paddle);
};
var step = function() {
update();
render();
animate(step);
};
function Paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.x_speed = 0;
this.y_speed = 0;
}
Paddle.prototype.render = function() {
context.fillStyle = "#0000FF";
context.fillRect(this.x, this.y, this.width, this.height);
};
Paddle.prototype.move = function(x, y) {
this.x += x;
this.y += y;
this.x_speed = x;
this.y_speed = y;
if (this.x < 0) {
this.x = 0;
this.x_speed = 0;
} else if (this.x + this.width > width) {
this.x = width - this.width;
this.x_speed = 0;
}
};
function Computer() {
this.paddle = new Paddle(width / 2 - 25, 10, 50, 10);
}
Computer.prototype.render = function() {
this.paddle.render();
};
Computer.prototype.update = function(ball) {
var x_pos = ball.x;
var diff = -((this.paddle.x + (this.paddle.width / 2)) - x_pos);
if (diff < 0 && diff < -4) {
diff = -5;
} else if (diff > 0 && diff > 4) {
diff = 5;
}
this.paddle.move(diff, 0);
if (this.paddle.x < 0) {
this.paddle.x = 0;
} else if (this.paddle.x + this.paddle.width > width) {
...