Vê se assim resolve...
P.S.: Dessa forma ele anda na diagonal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#canvas{
height: 400;
width: 400;
background-color: aquamarine;
}
.flex {
-webkit-flex: 1;
flex: 1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div class="flex">
<pre id="console-log"></pre>
</div>
<script>
var gameReady = true;
let consoleLog = document.getElementById('console-log')
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
var x = canvas.width/2 //começa no meio do x (player)
var y = canvas.height/2 //começa no meio do y (player)
var vel = 1
function messageLog(message) {
consoleLog.innerHTML += `${message}<br>`;
}
var Keys = {
up: false,
down: false,
left: false,
right: false
};
//objeto player com propriedades do quadrado
var player = {
color: 'black',
altura: '10',
largura: '10',
position: {
coordx: x,
coordy: y
}
}
//desestruturação do objeto player
var {color, altura, largura, position, mover} = player
//le a tecla digitada
window.onkeydown = function(e){
//messageLog(`Key "${event.key}" pressed [event: keypress]`);
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = true;
if(kc === 38) Keys.up = true;
if(kc === 39) Keys.right = true;
if(kc === 40) Keys.down = true;
}
window.onkeyup = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = false;
if(kc === 38) Keys.up = false;
if(kc === 39) Keys.right = false;
if(kc === 40) Keys.down = false;
}
function move() {
if(Keys.up) {
player.position.coordy -= vel;
}
if(Keys.down) {
player.position.coordy += vel;
}
if(Keys.left) {
player.position.coordx -= vel;
}
if(Keys.right) {
player.position.coordx += vel;
}
}
//desenha o player na tela
function draw() {
move()
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillRect(position.coordx, position.coordy, largura, altura)
ctx.fillStyle = color
requestAnimationFrame(draw) //looping do programa
}
//inicio do programa
draw();
</script>
</body>
</html>