跳到主要内容

动画压力测试

此示例创建 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,
});

/*
* 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();

操作说明: 此示例同时旋转 300 个矩形,以展示 Konva 的动画能力。观察这些图形在屏幕上流畅旋转。