跳到主要内容

使用 Konva 处理 HTML5 Canvas 键盘事件

Konva 没有 keydownkeyup 等内置键盘事件。

如何监听 Canvas 上的 keydown 或 keyup 事件?

你可以通过两种方式添加这些事件:

  1. 监听 window 对象上的全局事件
  2. 使用 tabIndex 属性让舞台容器可获得焦点,然后监听容器上的事件。

操作说明:单击舞台以使其获得焦点,然后使用方向键移动图形。

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const circle = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
});
layer.add(circle);

// make stage container focusable
stage.container().tabIndex = 1;
// focus it
// also stage will be in focus on its click
stage.container().focus();

const DELTA = 4;

// add keyboard events
stage.container().addEventListener('keydown', (e) => {
  if (e.keyCode === 37) {
    circle.x(circle.x() - DELTA);
  } else if (e.keyCode === 38) {
    circle.y(circle.y() - DELTA);
  } else if (e.keyCode === 39) {
    circle.x(circle.x() + DELTA);
  } else if (e.keyCode === 40) {
    circle.y(circle.y() + DELTA);
  } else {
    return;
  }
  e.preventDefault();
});