Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Uint8Array and Uint8ClampedArray

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?

like image 993
Luka Avatar asked Feb 17 '14 02:02

Luka


People also ask

What is Uint8ClampedArray?

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.

Is Uint8Array same as ArrayBuffer?

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.

What is Uint8Array used for?

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).

How do you concatenate Uint8Array?

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.


1 Answers

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 
like image 98
Felix Kling Avatar answered Sep 28 '22 04:09

Felix Kling