JSFiddle - React, Tailwind, and code Playground
HTML
<canvas width="500" height="500" id="canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var spacePressed = false;
document.addEventListener("keydown", d);
document.addEventListener("keyup", u);
function d(e) {
if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 39) {
rightPressed = true;
}
if (e.keyCode == 38) {
upPressed = true;
}
if (e.keyCode == 32) {
spacePressed = true;
}
}
function u(e) {
if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 39) {
rightPressed = false;
}
if (e.keyCode == 38) {
upPressed = false;
}
if (e.keyCode == 32) {
spacePressed = false;
}
}
function Vector(x, y) {
this.x = x || 0;
this.y = y || 0;
}
function Bullet(x, y, sx, sy) {
this.x = x;
this.y = y;
this.sx = sx;
this.sy = sy;
this.r = 1;
this.show = function() {
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
};
this.move = function() {
this.x += this.sx;
this.y += this.sy;
};
this.wrap = function() {
if (this.x > width+this.r) {
this.x = -this.r;
} else if (this.x < -this.r) {
this.x = width+this.r;
}
if (this.y > height+this.r) {
this.y = -this.r;
} else if (this.y < -this.r) {
this.y = height+this.r;
}
};
}
function Player() {
this.pos = new Vector(width/2, height/2);
this.r = 15;
this.heading = 0;
this.facingX = 0;
this.facingY = 0;
this.show = function() {
ctx.strokeStyle = "white";
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
ctx.rotate(this.heading);
ctx.beginPath();
ctx.moveTo(-this.r, this.r);
ctx.lineTo(this.r, this.r);
ctx.lineTo(0,...