JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="300" height="300">
<p>Sorry, but your browser does no support this HTML 5 element. </p>
<p>In order to run this game, please upgrade to the latest version<p>
<p>of FireFox, Chrome, Safari, or Opera.</p>
</canvas>
<p>Click the canvas and hit space to fire</p>
CSS
#canvas {
background: black;
border: 1px solid #000;
}
JavaScript
var canvas, ctx,
spaceKey = false,
upKey = false,
downKey = false,
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
done = true;
function Ball() {
this.x = 150;
this.y = 295;
}
Ball.prototype.draw = function(newx, newy) {
ctx.clearRect(this.x-5,this.y-5,600,20);
newx = newx || this.x;
newy = newy || this.y;
this.x = newx; this.y = newy;
var ball = this;
ctx.beginPath( );
ctx.arc(ball.x, ball.y,4,0,Math.PI * 2, false);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.closePath();
}
Ball.prototype.shootUp = function() {
var ball = this;
inter = setInterval(function () {
if(ball.x <= 0) clearInterval(inter);
ball.draw(ball.x, ball.y-20);
}, 100);
}
function loop() {
if (spaceKey) shoot();
}
function keyDown(e) {
if(e.keyCode == 32) spaceKey = true;
}
function keyUp(e) {
if (e.keyCode == 32) spaceKey = false;
}
function shoot() {
var currentBall = new Ball();
currentBall.draw();
currentBall.shootUp();
}
function init() {
setInterval(loop, 10);
window.addEventListener('keydown', keyDown, false);
window.addEventListener('keyup', keyUp, false);
};
init();