Skip to main content

动画压力测试

此演示创建了300个具有随机大小、位置和颜色的矩形,然后通过旋转每个矩形来对它们进行动画处理。通过将图层的 listening 属性设置为 false 来优化动画性能,这样可以提高绘制性能,因为矩形将不会被绘制到命中图上。

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

/*
 * 将 listening 属性设置为 false 将改善
 * 绘制性能,因为矩形不必被
 * 绘制到命中图上
 */
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();

说明: 此演示展示了 Konva 的动画能力,通过同时旋转300个矩形。观看这些形状在屏幕上平滑旋转。