Skip to main content

HTML5 Canvas 监听禁用性能提示

如果你在画布上有很多形状,并且不需要对其中某些形状检测事件, 你可以将 listening 设置为 false 来提高性能。

listening = false 时,该形状将被忽略事件检测(如鼠标悬停、拖放、点击等)。 这可以显著提高复杂应用的性能。

下面是一个演示,展示了监听形状与非监听形状之间的性能差异:

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

// 创建许多启用事件监听的圆圈
for (let i = 0; i < 100; i++) {
  const circle = new Konva.Circle({
    x: Math.random() * stage.width(),
    y: Math.random() * stage.height(),
    radius: 20,
    fill: 'blue',
    opacity: 0.5,
    // 启用事件检测(默认)
    listening: true,
  });
  
  // 添加悬停效果
  circle.on('mouseover', function() {
    this.fill('red');
  });
  
  circle.on('mouseout', function() {
    this.fill('blue');
  });
  
  layer.add(circle);
}

// 创建许多禁用事件监听的圆圈
for (let i = 0; i < 1000; i++) {
  const circle = new Konva.Circle({
    x: Math.random() * stage.width(),
    y: Math.random() * stage.height(),
    radius: 20,
    fill: 'green',
    opacity: 0.5,
    // 禁用事件检测以获得更好的性能
    listening: false,
  });
  layer.add(circle);
}

// 添加文本说明
const text = new Konva.Text({
  x: 10,
  y: 10,
  text: '蓝色圆圈(100)有事件监听(悬停它们)\n绿色圆圈(1000)没有监听(更好的性能)',
  fontSize: 16,
  fill: 'black',
});
layer.add(text);