Difference between Uint8Array and Uint8ClampedArray

亡梦爱人 提交于 2020-01-30 13:56:09

问题


What is the difference between Uint8Array and Uint8ClampedArray in JavaScript? I understand that Uint8ClampedArray is used with canvas for pixel manipulations. Why is that and what is the benefit?


回答1:


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

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 Uint8Array array just takes the first 8 bit of the value.

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


来源:https://stackoverflow.com/questions/21819870/difference-between-uint8array-and-uint8clampedarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!