Skip to main content

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

// 创建复杂的星形
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,
});

// 为了更好的性能缓存形状
star.cache();
layer.add(star);

// 创建不需要缓存的简单圆形
const circle = new Konva.Circle({
x: 100,
y: 100,
radius: 20,
fill: 'red',
});
layer.add(circle);

// 创建优化的动画
const anim = new Konva.Animation((frame) => {
// 旋转星形(缓存形状)
star.rotation(frame.time * 0.1);

// 圆形按圆形轨迹移动
circle.x(100 + Math.cos(frame.time * 0.002) * 50);
circle.y(100 + Math.sin(frame.time * 0.002) * 50);
}, layer);

// 添加开始/停止按钮
const button = document.createElement('button');
button.textContent = '切换动画';
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 = '开始动画';
} else {
anim.start();
button.textContent = '停止动画';
}
isPlaying = !isPlaying;
});

anim.start();