跳到主要内容

使用 Konva 取消 HTML5 Canvas 事件冒泡传播

要取消 Konva 中的事件冒泡传播,可以将事件对象的 cancelBubble 属性设置为 true。

操作说明:单击圆形。你会看到仅处理了圆形绑定的事件,因为触发圆形事件时取消了事件传播, 所以事件对象不会向上冒泡。

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

circle.on('click', function (evt) {
  alert('You clicked on the circle');
  // stop event bubble
  evt.cancelBubble = true;
});

layer.on('click', function () {
  alert('You clicked on the layer');
});

layer.add(circle);