← 中文资源

简体中文版本

Uint8ClampedArray 饱和截断字节而不回绕溢出

对比 Uint8ClampedArray 与 Uint8Array:前者把越界值饱和钳位在 0 到 255 并采用奇进偶舍,后者按 256 取模回绕,防止像素或信号通道溢出色偏。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

-25 -> clamped:   0 | wrapped: 231
  0.5 -> clamped:   0 | wrapped:   0
  1.5 -> clamped:   2 | wrapped:   1
  2.5 -> clamped:   2 | wrapped:   2
  255 -> clamped: 255 | wrapped: 255
  290 -> clamped: 255 | wrapped:  34
  NaN -> clamped:   0 | wrapped:   0
brightness +60 clamp: 255

实现说明

迭代发生在 for (let i = 0; i < inputs.length; i++) 内部——循环之外的语句只执行一遍。 演示用的数据放在这几个模块级绑定中:inputs、clamped、wrapped。

使用要点

  • 严格意义上无依赖——导入清单里没有任何包。
  • 每一步打印都带着自己的标签:brightness +60 clamp:。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 状态都挂在模块顶层:inputs、clamped、wrapped。

核心语句

const inputs = [-25, 0.5, 1.5, 2.5, 255, 290, NaN];
const clampCol = String(clamped[i]).padStart(3);
const inputCol = String(inputs[i]).padStart(5);

代码示例

const inputs = [-25, 0.5, 1.5, 2.5, 255, 290, NaN];

const clamped = new Uint8ClampedArray(inputs);
const wrapped = new Uint8Array(inputs);

for (let i = 0; i < inputs.length; i++) {
  const inputCol = String(inputs[i]).padStart(5);
  const clampCol = String(clamped[i]).padStart(3);
  const wrapCol = String(wrapped[i]).padStart(3);
  console.log(`${inputCol} -> clamped: ${clampCol} | wrapped: ${wrapCol}`);
}

// Note: 0.5 rounds to 0, 1.5 and 2.5 round to even (2), while negatives clamp to 0
console.log('brightness +60 clamp:', new Uint8ClampedArray([220 + 60])[0]);