跳到主要内容

使用 Konva 对 10,000 个带工具提示的图形进行压力测试

此示例展示如何高效处理大量图形(10,000 个圆形)和工具提示。将鼠标悬停在任意圆形上时,工具提示会显示其索引和颜色。

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

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