跳到主要内容

HTML5 Canvas 避免内存泄漏技巧

删除图形

remove()destroy() 是两个非常相似的方法。如果需要彻底删除节点,请使用 destroy()destroy() 方法从 KonvaJS 引擎中删除对该节点的所有引用。如果要重复使用节点,请使用 remove(),之后可以再次将该节点添加到任何容器。

补间

使用 Konva.Tween 实例时,必须在使用后将其销毁。

以下示例展示了正确的内存管理:

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 circle
const circle = new Konva.Circle({
  x: 100,
  y: 100,
  radius: 30,
  fill: 'red'
});

layer.add(circle);

// Add buttons
const addButton = document.createElement('button');
addButton.textContent = 'Add Circle';
document.body.appendChild(addButton);

const removeButton = document.createElement('button');
removeButton.textContent = 'Remove Circle';
document.body.appendChild(removeButton);

const animateButton = document.createElement('button');
animateButton.textContent = 'Animate';
document.body.appendChild(animateButton);

// Handle adding/removing
addButton.addEventListener('click', () => {
  layer.add(circle);
});

removeButton.addEventListener('click', () => {
  // Just remove from layer, can be added back
  circle.remove();
});

animateButton.addEventListener('click', () => {
  // Using to() method which auto-destroys the tween
  circle.to({
    x: Math.random() * stage.width(),
    y: Math.random() * stage.height(),
    duration: 1
  });
  
  // If using Tween directly, make sure to destroy it
  const tween = new Konva.Tween({
    node: circle,
    rotation: 360,
    duration: 1,
    onFinish: function() {
      // Clean up the tween
      tween.destroy();
    }
  }).play();
});