JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="game-canvas"></canvas>
JavaScript
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
let spaceshipX = 250;
let spaceshipY = 450;
let bulletX = spaceshipX + 40;
let bulletY = spaceshipY;
canvas.width = 500;
canvas.height = 500;
// move spaceship left and right
document.addEventListener('keydown', (event) => {
if (event.keyCode === 37) {
spaceshipX -= 10;
} else if (event.keyCode === 39) {
spaceshipX += 10;
}
});
//create the bullet and shoot when user click the mouse
canvas.addEventListener('click', (event) => {
bulletX = spaceshipX + 40;
bulletY = spaceshipY;
setInterval(() => {
bulletY -= 10;
draw();
if(bulletY < 0) {
clearInterval();
}
}, 50);
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "green";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//draw spaceship
ctx.fillStyle = "black";
ctx.fillRect(spaceshipX, spaceshipY, 80, 80);
//draw bullet
ctx.fillStyle = "yellow";
ctx.fillRect(bulletX, bulletY, 10, 20);
}
setInterval(draw, 10);