Skip to main content

HTML5 Canvas Optimize Animation Performance Tip

When creating animations with Konva, it's important to optimize them for better performance. Here are some key tips:

  1. Use Konva.Animation instead of requestAnimationFrame directly
  2. Only animate properties that need to change
  3. Use batchDraw() for multiple shape updates
  4. Consider using shape caching for complex shapes
  5. Minimize the number of nodes being animated

Below is a demo showing optimized animation techniques:

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

// Draw initial state
layer.draw();

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