JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
<title>KnifeGun</title>
</head>
<body>
<canvas id='canvas'></canvas>
</body>
</html>
JavaScript
$(document).ready(function() {
var width = 200;
var height = 300;
var canvas = $('#canvas')[0];
var ctx = canvas.getContext("2d");
gameLoop(canvas, ctx, width, height);
})
function gameLoop(canvas, ctx, width, height){
xPlayer = move()[0];
yPlayer = move()[1];
draw(canvas, ctx, width, height);
player(canvas, ctx, xPlayer, yPlayer);
}
function move(){
var posPlayer = new Array(2);
posPlayer[0] = null;
posPlayer[1] =null;
$(document).keydown(function(curKey) {
switch(curKey.which){
case 87:
posPlayer[1] += 50;
break;
case 83:
posPlayer[1] -= 1;
break;
case 65:
posPlayer[0] -= 1;
break;
case 68:
posPlayer[0] += 1;
break;
}
});
return posPlayer;
}
function draw(canvas, ctx, width, height){
canvas.width = width;
canvas.height = height;
ctx.fillStyle = "#ccc";
ctx.fillRect (0, 0, width, height);
}
function player(canvas, ctx, xPlayer, yPlayer){
ctx.fillStyle = "#333";
ctx.fillRect (xPlayer, yPlayer, 20, 20);
}