如何使用箭头键在 Canvas 上绘图?

How do I draw on Canvas using arrow keys?

我正在尝试制作一个绘图程序,用户可以在其中使用键盘绘图。但是我无法让该行显示在屏幕上。 此外,console.log(lastX/lastY) 不输出任何内容,因此我不确定它是否正在执行任何操作或者我的代码是否有问题。

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';


//object to keep track of when keys are pressed
let keysPressed = {};

//amount to move by
let moveAmount = 10;


document.addEventListener('keydown', (event) => {

  // if key pressed is an arrow key
   //left
   if (keysPressed[37]) {
    //console.log('left');
    lastX -= moveAmount;
  }
  //up
  else if (keysPressed[37]) {
    //console.log('up');
    lastY -= moveAmount;
  }
  //right
  else if (keysPressed[37]) {
   // console.log('right');
    lastX += moveAmount;
  }
  //down
  else if(keysPressed[37]) {
   // console.log('down');
    lastY += moveAmount;
  }

    // 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.stroke();
});
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/

这是您可以使用键盘在 canvas 上绘图的最基本操作。

您代码中的主要问题是 if 语句以及未声明 lastX 和 lastY。