HTML5 Canvas 键盘事件与 Konva

HTML5 Canvas 键盘事件与 Konva

在 Konva 中没有内置的键盘事件,比如 keydownkeyup

那么如何在画布上监听 keydown 或 keyup 事件呢?

你可以通过两种方式轻松添加它们:

  1. 监听 window 对象上的全局事件
  2. 或者使舞台容器可聚焦,使用 tabIndex 属性并在其上监听事件。

指令:点击舞台以聚焦,使用箭头键移动形状

HTML5 Canvas 键盘事件view raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Canvas Keyboard events Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

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

var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2 + 10,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});

layer.add(circle);

var container = stage.container();

// make it focusable

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

const DELTA = 4;

container.addEventListener('keydown', function (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();
});
</script>
</body>
</html>