跳到主要内容

使用 Konva 触发 HTML5 Canvas 事件

要使用 Konva 触发事件,可以使用 fire() 方法。 此方法可以通过编程方式触发 clickmouseovermousemove 等事件, 也可以触发 foo 和 bar 等自定义事件。

注意:虽然可以使用自定义事件,但通常最好使用 clickmouseovermousemove 等内置交互事件。自定义事件会增加代码的维护和调试难度。

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: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});

// add shape event listener
circle.on('customEvent', function (evt) {
alert('custom event fired');
});

// add button to trigger custom event
const button = document.createElement('button');
button.innerHTML = 'Fire Custom Event';
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
button.style.zIndex = '1';
document.body.appendChild(button);
button.addEventListener('click', () => {
// fire custom event
circle.fire('customEvent', {
bubbles: true,
});
});

layer.add(circle);