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'),
BulletRenderer = function(){
var bullets = [];
this.push = function(bullet){
bullets.push(bullet);
};
this.render = function(){
for (var i in bullets){
if (bullets[i].active){
bullets[i].update();
bullets[i].draw();
} else {
delete bullets[i];
}
}
};
return this;
}();
function Bullet(){
this.x = 150;
this.y = 280;
this.velX = 0;
this.velY = -1;
this.active = true;
this.update = function(){
this.y += this.velY;
if (this.y < 0){
this.active = false;
}
};
this.draw = function(){
ctx.beginPath();
ctx.arc(this.x, this.y,4,0,Math.PI * 2, false);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.closePath();
};
};
function loop() {
canvas.width = canvas.width;
if (spaceKey) shoot();
BulletRenderer.render();
}
function keyDown(e) {
if (e.keyCode == 32) spaceKey = true;
}
function keyUp(e) {
if (e.keyCode == 32) spaceKey = false;
}
function shoot() {
BulletRenderer.push(new Bullet());
}
(function init() {
setInterval(loop, 10);
document.addEventListener('keydown', keyDown, false);
document.addEventListener('keyup', keyUp, false);
})();
//init();