JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas id="canv" height="300" width="300">
</canvas>
</body>
CSS
body{
background-color:black;
}
canvas{
background-color:white;
}
JavaScript
var c=document.getElementById("canv");
var canv=c.getContext("2d");
console.log("test");
var map = {};
var playerlist=[];
function player(width,height,x,y,color,speedx,speedy){
this.width=width;
this.height=height;
this.x=x;
this.y=y;
this.color=color;
this.speedx=speedx;
this.speedy=speedy;
playerlist.push(this);
}
var player1=new player(50,50,0,0,"red",2,2);
console.log(playerlist[0]);
function gravity(playerY){
}
function createplayerlistener(name,key1,key2,key3,key4){
onkeydown = onkeyup = function(e){
e = e || event;
map[e.keyCode] = e.type == 'keydown';
if(name.x+name.speedx<c.width-name.width){
if(map[key1]){
name.x+=name.speedx;
}}
if(name.x+name.speedx>0){
if(map[key2]){
name.x-=name.speedx;
}
}
if(name.y+name.speedy<c.height-name.height){
if(map[key3]){
name.y+=name.speedy;
}}
if(name.y+name.speedy>0){
if(map[key4]){
name.y-=name.speedy;
}}
}
}
createplayerlistener(player1,39,37,40,38);
setInterval(function(){
canv.clearRect(0,0,c.width,c.height);
for(var i=0;i<=playerlist.length-1;i++){canv.fillStyle=playerlist[i].color;// iterates through players and draws them
canv.fillRect(playerlist[i].x,playerlist[i].y,playerlist[i].width,playerlist[i].height);}
},10);