← 返回首页

Canvas 2D 游戏性能优化:从 30fps 到稳定 60fps

Independent developer · MIT licensed
一个纯 Canvas 的小游戏,性能瓶颈通常在三个地方:重绘、状态切换、GC。

一、别每帧都重建对象

最常见的性能杀手是在 requestAnimationFrame 里创建临时对象(数组、对象字面量)。60fps 下每秒创建 60 次,GC 压力很大,表现为间歇性卡顿。

// 差:每帧新建数组
function update() {
  const matches = findMatches();  // 内部每次 new Array
}

// 好:复用缓冲 const matchBuffer = []; function update() { matchBuffer.length = 0; findMatchesInto(matchBuffer); }

二、减少状态切换

Canvas 的 fillStyle、beginPath、fill 这些调用有开销。按颜色分组绘制比逐个绘制快:

// 慢:每个宝石都设置一次颜色
for (const gem of gems) {
  ctx.fillStyle = gem.color;
  ctx.fillRect(gem.x, gem.y, gem.size, gem.size);
}

// 快:按颜色分组批量画 const byColor = groupBy(gems, g => g.color); for (const [color, group] of byColor) { ctx.fillStyle = color; for (const gem of group) { ctx.fillRect(gem.x, gem.y, gem.size, gem.size); } }

在我的 8x8 棋盘(64 个宝石)上,这个改动把单帧绘制时间从约 2.1ms 降到 1.3ms。

三、脏矩形重绘

整屏重绘在棋盘类游戏里是浪费。只有变化的格子需要重绘:

// 只重绘被消除/下落的区域
ctx.save();
ctx.beginPath();
ctx.rect(dirtyX, dirtyY, dirtyW, dirtyH);
ctx.clip();
redrawRegion(dirtyX, dirtyY, dirtyW, dirtyH);
ctx.restore();

注意:脏矩形方案要处理好重叠和边界,比全屏重绘复杂,小游戏(如 8x8 棋盘)收益有限——先测量再优化。

四、避免在高频路径里用字符串拼接

fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')' 每次拼接都产生新字符串。预计算成数组:

const COLOR_CACHE = new Map();
function colorOf(r, g, b) {
  const k = (r<<16) | (g<<8) | b;
  let v = COLOR_CACHE.get(k);
  if (!v) {
    v = rgb(${r},${g},${b});
    COLOR_CACHE.set(k, v);
  }
  return v;
}

五、测量工具

不要凭感觉优化。用 performance.now() 包住可疑代码段:

const t0 = performance.now();
drawBoard();
const dt = performance.now() - t0;
if (dt > 8) console.warn('drawBoard slow:', dt.toFixed(2), 'ms');

60fps 的预算是 16.6ms/帧,其中绘制通常应控制在 8ms 以内,留出逻辑计算和浏览器合成的时间。

我的实现

这些优化都用在《宝石三连》里了(8x8 棋盘、5 种宝石、纯 Canvas 2D、无图片资源)。

---

如果这篇对你有帮助,欢迎 star。

The full Match3 engine source — MIT licensed, read the code before you commit to it.

View the source on GitHub Play the demo