跳到主要内容

HTML5 Canvas 优化描边性能技巧

在 Konva 中绘制同时具有描边和阴影的图形时,会执行一个额外的内部绘制步骤。 这是因为 Konva 需要确保正确绘制描边的阴影。 但是,这会影响性能,尤其是在处理大量图形时。

要优化性能,可以设置 shadowForStrokeEnabled(false) 以禁用描边阴影。 当不需要描边投射阴影时,此设置特别有用。

以下示例展示了启用和禁用描边阴影时的性能差异:

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 shape with shadow for stroke (default)
const circleWithShadow = new Konva.Circle({
  x: 100,
  y: 100,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
  shadowColor: 'black',
  shadowBlur: 10,
  shadowOffset: { x: 5, y: 5 },
  shadowOpacity: 0.5,
});

// Create shape without shadow for stroke (optimized)
const circleOptimized = new Konva.Circle({
  x: 250,
  y: 100,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
  shadowColor: 'black',
  shadowBlur: 10,
  shadowOffset: { x: 5, y: 5 },
  shadowOpacity: 0.5,
  shadowForStrokeEnabled: false,
});

// Add labels
const defaultLabel = new Konva.Text({
  x: 50,
  y: 170,
  text: 'With Stroke Shadow',
  fontSize: 16,
});

const optimizedLabel = new Konva.Text({
  x: 200,
  y: 170,
  text: 'Without Stroke Shadow\n(Better Performance)',
  fontSize: 16,
});

// Add FPS counter
const fpsText = new Konva.Text({
  x: 10,
  y: 10,
  text: 'FPS: 0',
  fontSize: 16,
});

layer.add(circleWithShadow);
layer.add(circleOptimized);
layer.add(defaultLabel);
layer.add(optimizedLabel);
layer.add(fpsText);

// Create animation to demonstrate performance
const anim = new Konva.Animation((frame) => {
  circleWithShadow.rotation(frame.time * 0.1);
  circleOptimized.rotation(frame.time * 0.1);
  
  // Update FPS counter
  fpsText.text('FPS: ' + frame.frameRate.toFixed(1));
}, layer);

anim.start();