Skip to main content

Animation Stress Test

This demo creates 300 rectangles with random sizes, positions, and colors, then animates them by rotating each rectangle. The animation performance is optimized by setting the listening property of the layer to false, which improves drawing performance as the rectangles won't be drawn onto the hit graph.

import Konva from 'konva';

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

function update(layer, frame) {
  const angularSpeed = 100;
  const angularDiff = (angularSpeed * frame.timeDiff) / 1000;
  const shapes = layer.getChildren();

  for (let n = 0; n < shapes.length; n++) {
    const shape = shapes[n];
    shape.rotate(angularDiff);
  }
}

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

/*
 * setting the listening property to false will improve
 * drawing performance because the rectangles won't have to be
 * drawn onto the hit graph
 */
const layer = new Konva.Layer({
  listening: false,
});

const colors = [
  'red',
  'orange',
  'yellow',
  'green',
  'blue',
  'cyan',
  'purple',
];
let colorIndex = 0;

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

  const randWidth = Math.random() * 100 + 20;
  const randHeight = Math.random() * 100 + 20;
  const randX = Math.random() * stage.width() - 20;
  const randY = Math.random() * stage.height() - 20;

  const box = new Konva.Rect({
    x: randX,
    y: randY,
    offset: {
      x: randWidth / 2,
      y: randHeight / 2,
    },
    width: randWidth,
    height: randHeight,
    fill: color,
    stroke: 'black',
    strokeWidth: 4,
  });

  layer.add(box);
}

stage.add(layer);

const anim = new Konva.Animation(function (frame) {
  update(layer, frame);
}, layer);

anim.start();

Instructions: This demo shows the animation capability of Konva by rotating 300 rectangles simultaneously. Watch as the shapes rotate smoothly across the screen.