Как рисовать на холсте с помощью клавиш со стрелками? - PullRequest
0 голосов
/ 12 марта 2020

Я пытаюсь создать программу для рисования, в которой пользователи могут рисовать с клавиатуры. Однако я не могу заставить линию отображаться на экране. Кроме того, файл 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();
});

1 Ответ

0 голосов
/ 12 марта 2020
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 не объявлены.

...