Skip to main content

HTML5 Canvas Canvas 多事件绑定教程

在 Konva 中,要为单个处理函数绑定多个事件,可以使用 on() 方法,并传入一个以空格分隔的多个事件类型字符串。

shape.on('mouseover mousedown mouseup', function (e) {
console.log('events: ' + e.type);
});

操作说明:在圆形上执行 mouseover、mousedown 和 mouseup 事件,以观察绑定在圆形上的函数在每个事件触发时都会执行。

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);
}

circle.on('mouseover mousedown mouseup', function (evt) {
  writeMessage('event: ' + evt.type);
});

layer.add(circle);