Skip to main content

Drag and Drop Stress Test with 10,000 Shapes

This example demonstrates a stress test with 10,000 shapes. For simplicity, we're using just two layers - one main layer for all shapes and one dedicated drag layer. When we drag a shape, it's moved to the separate drag layer to ensure smooth movement.

import Konva from 'konva';

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

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

// Create main layer for all shapes
const mainLayer = new Konva.Layer();

// Create a dedicated layer for dragging
const dragLayer = new Konva.Layer();

// Define colors for random shapes
const colors = [
  'red',
  'orange',
  'yellow',
  'green',
  'blue',
  'cyan',
  'purple',
];
let colorIndex = 0;

// Helper function to add a circle to a layer
function addCircle(layer) {
  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: 6,
    fill: color,
  });

  layer.add(circle);
}

// Create 10,000 circles on the main layer
for (let n = 0; n < 10000; n++) {
  addCircle(mainLayer);
}

// Add the main layer and drag layer to the stage
stage.add(mainLayer);
stage.add(dragLayer);

// Setup drag and drop behavior
stage.on('mousedown', function (evt) {
  const circle = evt.target;
  
  // Only handle circle shapes (ignore clicks on empty space)
  if (!circle || circle.getClassName() !== 'Circle') {
    return;
  }
  
  // Move the circle to the drag layer
  circle.moveTo(dragLayer);
  circle.startDrag();
});

// When dragging stops, move the circle back to the main layer
stage.on('mouseup', function (evt) {
  const circle = evt.target;
  
  // Only handle circle shapes
  if (!circle || circle.getClassName() !== 'Circle') {
    return;
  }
  
  // Move the circle back to the main layer
  circle.moveTo(mainLayer);
});