Skip to main content

10,000 Shapes with Tooltips Stress Test with Konva

This demo shows how to handle a large number of shapes (10,000 circles) with tooltips efficiently. When you hover over any circle, a tooltip will show its index and color.

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

const stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height,
});

const circlesLayer = new Konva.Layer();
const tooltipLayer = new Konva.Layer();
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'cyan', 'purple'];
let colorIndex = 0;

for (let i = 0; i < 10000; i++) {
  const color = colors[colorIndex++];
  if (colorIndex >= colors.length) {
    colorIndex = 0;
  }

  const randX = Math.random() * stage.width();
  const randY = Math.random() * stage.height();
  const circle = new Konva.Circle({
    x: randX,
    y: randY,
    radius: 3,
    fill: color,
    name: i.toString(),
  });

  circlesLayer.add(circle);
}

const tooltip = new Konva.Text({
  text: '',
  fontFamily: 'Calibri',
  fontSize: 12,
  padding: 5,
  visible: false,
  fill: 'black',
  opacity: 0.75,
  textFill: 'white',
});

tooltipLayer.add(tooltip);
stage.add(circlesLayer);
stage.add(tooltipLayer);

circlesLayer.on('mousemove', (e) => {
  const mousePos = stage.getPointerPosition();
  tooltip.position({
    x: mousePos.x + 5,
    y: mousePos.y + 5,
  });
  tooltip.text('node: ' + e.target.name() + ', color: ' + e.target.fill());
  tooltip.show();
});

circlesLayer.on('mouseout', () => {
  tooltip.hide();
});