javascript Uint8Array 和 Uint8ClampedArray 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21819870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:45:38  来源:igfitidea点击:

Difference between Uint8Array and Uint8ClampedArray

javascriptarraysmemory-managementclamp

提问by Luka

What is the difference between Uint8Arrayand Uint8ClampedArrayin JavaScript? I understand that Uint8ClampedArrayis used with canvas for pixel manipulations. Why is that and what is the benefit?

JavaScript 中Uint8Array和之间有什么区别Uint8ClampedArray?我知道它Uint8ClampedArray与画布一起用于像素操作。为什么会这样,有什么好处?

回答by Felix Kling

Looking at the examples for Uint8ClampedArrayand Uint8Array, it looks like the difference is how values are treated when assigned.

查看Uint8ClampedArrayUint8Array的示例,看起来区别在于分配时如何处理值。

If you are trying to set one element to a clamped array to any value outside of the range 0-255, it will simply default to 0 or 255 (depending on whether the value is smaller or larger). A normal Uint8Arrayarray just takes the first 8 bit of the value.

如果您尝试将一个元素设置为范围之外的任何值的钳位数组0-255,它将简单地默认为 0 或 255(取决于该值是更小还是更大)。普通Uint8Array数组只取值的前 8 位。

Examples:

例子:

var x = new Uint8ClampedArray([17, -45.3]);
console.log(x[0]); // 17
console.log(x[1]); // 0
console.log(x.length); // 2

var x = new Uint8Array([17, -45.3]);
console.log(x[0]); // 17
console.log(x[1]); // 211
console.log(x.length); // 2