You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对平坦数组按块执行reverse操作 实现像素动画帧顺序反转

解决方案

方案1:直接对平坦数组做定长块反转

你需要的是定长块反转能力,即按固定长度拆分数组后反转块顺序,块内内容保持不变,适配Uint8Array的实现如下:

/**
 * 定长块反转平坦数组
 * @param {Uint8Array} source 原始存储数组
 * @param {number} blockSize 单块字节长度(你的场景传入72即可)
 * @returns {Uint8Array} 块反转后的新数组
 */
function reverseBlocks(source, blockSize) {
  const totalBlocks = Math.floor(source.length / blockSize);
  const result = new Uint8Array(source.length);
  for (let i = 0; i < totalBlocks; i++) {
    const sourceOffset = (totalBlocks - 1 - i) * blockSize;
    const targetOffset = i * blockSize;
    result.set(source.subarray(sourceOffset, sourceOffset + blockSize), targetOffset);
  }
  return result;
}

// 用你的示例测试
const myArr = new Uint8Array([1,2,3,4,5,6,7,8]);
console.log(reverseBlocks(myArr, 2)); // 输出:Uint8Array(8) [7, 8, 5, 6, 3, 4, 1, 2]

该实现全程操作一维数组,无需转二维结构,TypedArray的subarray为视图操作不产生额外复制,set为批量写入,性能表现优异。

方案2:适配动画渲染场景的零成本方案

由于你提到每帧渲染依赖前一帧的信息,完全不需要修改原始存储结构,只需要预生成倒序的帧索引列表即可:

  • 你共有5帧,倒放对应的帧索引序列为 [4,3,2,1,0]
  • 渲染时按顺序遍历索引序列,第n次渲染取索引为index = 序列[n]的帧,对应数据起始位置为index * 72,连续取72个字节渲染即可
  • 该方案不需要额外开辟内存存储反转后的数组,也不需要做任何数组修改操作,性能和内存占用都是最优的,完美适配差分帧依赖前序帧的渲染场景。

内容的提问来源于stack exchange,提问作者user16553022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:15:03