JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE HTML>
<html>
<body onload="init();">
<div id="gameArea">
<canvas id="viewport" width="800" height="400"></canvas>
</div>
</body>
</html>
CSS
html,body{width:100%;height:100%;margin:0px;}
#gameArea{width:800px;height:400px;margin:0px auto;}
#viewport{border:1px solid #000;margin:5px 0px 0px;}
JavaScript
var viewport = document.getElementById('viewport');
var ctx = viewport.getContext('2d');
console.log(ctx);
var fps = 30;
function init(){
setInterval(update, 1000 / fps);
}
function Player(){
this.width = 10;
this.height = 50;
this.X = 10;
this.Y = (viewport.height / 2) - (this.height / 2);
this.draw = function() {
ctx.fillStyle = '#0000ff';
ctx.fillRect(this.X, this.Y, this.width, this.height);
};
}
var player = new Player();
function Bot(){
this.width = 10;
this.height = 50;
this.X = 780;
this.Y = (viewport.height / 2) - (this.height / 2);
this.draw = function() {
ctx.fillStyle = '#ff0000';
ctx.fillRect(this.X, this.Y, this.width, this.height);
};
}
var bot = new Bot();
function Ball(){
this.radius = 5;
this.Y = (viewport.height / 2) - this.radius;
this.X = (viewport.width / 2) - this.radius;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.closePath();
ctx.fillStyle = '#00ff00';
ctx.fill();
};
}
function moveBall(){
this.speed = 2.5;
this.direction = 2;
if(this.direction == 1){
ball.X +=this.speed;
}
else if(this.direction == 2){
ball.X -=this.speed;
}
}
function collision(){
if(ball.X == 500){
moveBall.direction = 2;
alert(moveBall.direction);
}
if(ball.X == 300){
moveBall.direction = 1;
alert(moveBall.direction);
}
}
var ball = new Ball();
function draw(){
player.draw();
bot.draw();
ball.draw();
}
function update(){
ctx.clearRect(0, 0, viewport.width, viewport.height);
draw();
collision();
moveBall();
}