The type array of JS can be broadly divided into 3 categories: unsigned integers, signed integers, floating-point numbers.
Int8array; Uint8array; Uint8clampedarray; Int16array; Uint16array; Int32array; Uint32array; Float32array; Float64array;
Basically can be words too literally, look at the name to know how to go.
But with one exception uint8clampedarray, it is quite similar to Uint8array, but it is different.
Because the color data is exactly all 8-bit binary unsigned integers, these two types are often used when working with canvas drawing data.
Uint8clampedarray is mainly used in some special scenes, typical is ImageData.
The literal meaning of the word clamped is "fastened, clamped".
If the value entered is already an integer between 0~255, then Uint8array is consistent with the final result of Uint8clampedarray.
The difference between Uint8array and Uint8clampedarray is that the conversion logic of the input values that are not in the range (integers between the 0~255) is processed.
The conversion logic used by Uint8array is ToUint8.
One of the key points is that it takes the input number and 256 modulo, converts 8 bits to a positive integer, and it does not round.
So new Uint8array ([33.999]) is equivalent to new Uint8array ([33.111])
It is important to note that for negative numbers, because the binary storage form of negative numbers is in complement form, the relationship between the converted value and the input value is not intuitive.
For example-23, the binary is 11101001 233 (23 of the binary is 00010111, its complement is 11101001),
So new Uint8array ([-23]) is equivalent to new Uint8array ([233])
The detailed rules are as follows:
- Let number is tonumber (argument).
- Returnifabrupt (number).
- If number is NaN, +0,? 0, +∞, or? ∞, return +0.
- let int is sign (number) Xfloor (number).
- Let int8bit is int modulo 28.
- Return Int8bit.
The conversion logic used by Uint8clampedarray is Touint8clamp
It will put negative numbers in 0, more than 255 of the number is classified into 255, so the modulo will not be used.
So new Uint8clampedarray ([-23]) is equivalent to new Uint8clampedarray ([ 0 ])
It says that new Uint8array ([-23]) is equivalent to new Uint8array ([ 233 ]), so you can see the difference.
In addition, it does not take rounding, but rather rounds, but not rounding like Math.Round (), but with a method called banker rounding.
The detailed rules are as follows:
- Let number is tonumber (argument).
- Returnifabrupt (number).
- If number is NaN, return +0.
- If number≤0, return +0.
- If number≥255, return 255.
- Let f is floor (number).
- If F + 0.5 < number, then return F + 1.
- If number < F + 0.5, then return F.
- If f is odd and then return F + 1.
- Return F.
Reference
- TypedArray (MDN)
- Uint8clampedarray Object (MSDN)
- Type Conversion (ECMA-262)
Javascript TypedArray Doubts: The difference between Uint8array and Uint8clampedarray