跳到主要内容

Konva 的 HTML5 Canvas 特殊舞台事件

所有事件都从图形开始。因此,如果单击 Canvas 内的空白区域,click 事件不会在 Layer 上触发,而会在 Stage 对象上触发。

操作说明:单击空白区域和图形,查看不同的事件行为。

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 text = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black',
});
layer.add(text);

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

function writeMessage(message) {
text.text(message);
}

// handle stage click
stage.on('click', function (e) {
if (e.target === stage) {
writeMessage('clicked on stage');
return;
}
writeMessage('clicked on ' + e.target.name());
});

// add shape
circle.name('circle');
layer.add(circle);