Skip to main content

HTML5 Canvas Listening False Performance Tip

If you have a lot of shapes on the canvas and you don't need to detect events for some of them, you can set listening to false to improve performance.

When listening = false, the shape will be ignored from event detection (like mouseover, drag and drop, click, etc). This can significantly improve performance for complex applications.

Below is a demo showing the performance difference between listening and non-listening shapes:

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

// Create many circles with listening enabled
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,
// Enable event detection (default)
listening: true,
});

// Add hover effect
circle.on('mouseover', function() {
this.fill('red');
});

circle.on('mouseout', function() {
this.fill('blue');
});

layer.add(circle);
}

// Create many circles with listening disabled
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,
// Disable event detection for better performance
listening: false,
});
layer.add(circle);
}

// Add text explanation
const text = new Konva.Text({
x: 10,
y: 10,
text: 'Blue circles (100) have event listeners (hover them)\nGreen circles (1000) have no listeners (better performance)',
fontSize: 16,
fill: 'black',
});
layer.add(text);