JSFiddle - React, Tailwind, and code Playground
by Nathan Piper
HTML
<canvas id='player' width=400 height=400 style='border: 1px solid black'></canvas>
<canvas id='background' width=400 height=400 style='border: 1px solid black'></canvas>
<canvas id='enemy' width=400 height=400 style='border: 1px solid black'></canvas>
<canvas id='GUI' width=400 height=400 style='border: 1px solid black'></canvas>
CSS
canvas {
position: absolute;
top: 0;
left: 0;
}
#background{
background: black;
}
JavaScript
var FPS = 60;
var width = 400;
var height = 400;
var gBackground = document.getElementById('background').getContext('2d');
var gPlayer = document.getElementById('player').getContext('2d');
var gEnemy = document.getElementById('enemy').getContext('2d');
var gGUI = document.getElementById('GUI').getContext('2d');
var x = 50;
var y = 50;
var stars = [];
var player = {
width: 16,
height: 16,
x: (width/2) - 8,
y: height - 20,
speed: 5,
render: function () {
gPlayer.fillStyle = 'green';
gPlayer.fillRect(this.x, this.y, this.width, this.height);
},
tick: function () {
if(Key.left && this.x > 0) this.x -= this.speed;
if(Key.right && this.x < height-20) this.x += this.speed;
}
};
var Key = {
left: false,
right: false,
space: false
};
addEventListener("keydown", function (e) {
var keyCode = (e.keyCode) ? e.keyCode : e.which;
switch(keyCode){
case 37:
Key.left = true;
break;
case 39:
Key.right = true;
break;
case 32:
Key.space = true;
}
}, false);
addEventListener("keyup", function (e) {
var keyCode = (e.keyCode) ? e.keyCode : e.which;
switch(keyCode){
case 37:
Key.left = false;
break;
case 39:
Key.right = false;
break;
case 32:
Key.space = false;
}
}, false);
function collision(obj1, obj2) {
return (
obj1.x < obj2.x + obj2.width && obj1.x + obj1.width > obj2.x && obj1.y < obj2.y + obj2.height && obj1.y + obj1.height > obj2.y);
}
var Star = function (x, y) {
this.x = x;
this.y = y;
this.size = Math.floor(Math.random() * 3);
this.render = function () {
gBackground.fillStyle = 'white';
gBackground.fillRect(this.x, this.y, this.size, this.size);
};
this.tick = function () {
if(this.y > height + 4){
var index = stars.indexOf(this);
...