跳到主要内容

HTML5 Canvas 优化动画性能技巧

使用 Konva 创建动画时,需要优化动画以提高性能。 以下是一些主要技巧:

  1. 使用 Konva.Animation,而不是直接使用 requestAnimationFrame
  2. 仅对需要变化的属性应用动画
  3. 考虑为复杂图形使用缓存
  4. 尽量减少应用动画的节点数量

以下示例展示了经过优化的动画技巧:

import Konva from 'konva';

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

const layer = new Konva.Layer();
stage.add(layer);

// Create a complex star shape
const star = new Konva.Star({
x: stage.width() / 2,
y: stage.height() / 2,
numPoints: 6,
innerRadius: 40,
outerRadius: 70,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
});

// Cache the shape for better performance
star.cache();
layer.add(star);

// Create simple circle that doesn't need caching
const circle = new Konva.Circle({
x: 100,
y: 100,
radius: 20,
fill: 'red',
});
layer.add(circle);

// Create optimized animation
const anim = new Konva.Animation((frame) => {
// Rotate star (cached shape)
star.rotation(frame.time * 0.1);

// Move circle in a circle pattern
circle.x(100 + Math.cos(frame.time * 0.002) * 50);
circle.y(100 + Math.sin(frame.time * 0.002) * 50);
}, layer);

// Add start/stop button
const button = document.createElement('button');
button.textContent = 'Toggle Animation';
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
document.body.appendChild(button);

let isPlaying = true;
button.addEventListener('click', () => {
if (isPlaying) {
anim.stop();
button.textContent = 'Start Animation';
} else {
anim.start();
button.textContent = 'Stop Animation';
}
isPlaying = !isPlaying;
});

anim.start();