const canvas = document.querySelector('canvas');
const { width, height } = canvas;
// set the join, cap and width for lines
const ctx = canvas.getContext('2d');
//ctx.lineJoin = 'round';
//ctx.lineCap = 'round';
//ctx.lineWidth = 15;
//ctx.strokeStyle = 'black';
ctx.fillStyle = "black";
//object to keep track of when keys are pressed
//let keysPressed = {};
//amount to move by
let moveAmount = 2;
let lastX = 0;
let lastY = 0;
document.addEventListener('keydown', (event) => {
// if key pressed is an arrow key
//left
if (event.keyCode === 37) {
//console.log('left');
lastX -= moveAmount;
}
//up
else if (event.keyCode === 38) {
//console.log('up');
lastY -= moveAmount;
}
//right
else if (event.keyCode === 39) {
// console.log('right');
lastX += moveAmount;
}
//down
else if(event.keyCode === 40) {
// console.log('down');
lastY += moveAmount;
}
console.log(lastX, lastY)
// prevent normal arrow functionality
event.preventDefault();
// keep track of keys pressed
//keysPressed[event.key] = true;
//console.log(keysPressed);
// start the path with old x, y
ctx.beginPath();
// set new coordinates based on movement amount
ctx.moveTo(lastX, lastY);
// draw the path
ctx.fillRect(lastX, lastY, moveAmount , moveAmount );
});
https://jsfiddle.net/xwdru7am/
Это самая базовая c вещь, которую вы можете сделать, чтобы нарисовать на холсте с помощью клавиатуры.
Основное проблемы в вашем коде - это операторы if, а lastX и lastY не объявлены.