如何在组中使用按键事件?
How can I use a keydown event in a group?
我正在研究一个由矩形和变换器组成的组,现在需要用鼠标以外的方式移动它。使用容器我可以使用箭头键移动它但是对于组Keydown功能不起作用,我已经尝试使用group.on但没有成功。
我希望当点击箭头时它会开始在移动它的组中工作。
您无法使用 Konva
在 canvas 个节点(例如 Group
或 Shape
)上监听键盘事件。但是你可以很容易地模仿它。
您可以使 Stage
节点可聚焦并监听其上的键盘事件。然后在事件处理程序中执行所需的操作。
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();
layer.batchDraw();
});
我正在研究一个由矩形和变换器组成的组,现在需要用鼠标以外的方式移动它。使用容器我可以使用箭头键移动它但是对于组Keydown功能不起作用,我已经尝试使用group.on但没有成功。
我希望当点击箭头时它会开始在移动它的组中工作。
您无法使用 Konva
在 canvas 个节点(例如 Group
或 Shape
)上监听键盘事件。但是你可以很容易地模仿它。
您可以使 Stage
节点可聚焦并监听其上的键盘事件。然后在事件处理程序中执行所需的操作。
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();
layer.batchDraw();
});