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'),
shotX = 150, shotY = 280;
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() {
setTimeout(function() { if (shotY > 0) {
ctx.clearRect(shotX-5,shotY-5,600,20);
ctx.beginPath();
ctx.arc(shotX, shotY,4,0,Math.PI * 2, false);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.closePath();
shotY = shotY - 1;
shoot();
} else
ctx.clearRect(shotX-5,shotY-5,600,20);
}, 100);
}
(function init() {
setInterval(loop, 10);
document.addEventListener('keydown', keyDown, false);
document.addEventListener('keyup', keyUp, false);
})();
//init();