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?
The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set.
Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”. Uint16Array – treats every 2 bytes as an integer, with possible values from 0 to 65535.
The Uint8Array() constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
You can use the set method. Create a new typed array with all the sizes. Example: var arrayOne = new Uint8Array([2,4,8]); var arrayTwo = new Uint8Array([16,32,64]); var mergedArray = new Uint8Array(arrayOne.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With