92

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?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Luka
  • 2,779
  • 3
  • 17
  • 32

1 Answers1

123

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
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 31
    Note also that `Uint8Array([0.9])` is `[0]`, but `Uint8ClampedArray([0.9])` is `[1]`, ie. the clamped version uses rounding, but the basic version uses floor. – dan-man May 16 '16 at 09:22
  • 1
    The OP mentioned this was used for pixel values in the canvas, is this a shortcut for saturated arithmetic? – Indolering Sep 30 '16 at 19:54
  • @Felix, So `Uint8Array` is more performant because no bounds checking need be done? – Pacerier Mar 22 '17 at 15:59
  • Also [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) is created from an `Uint8ClampedArray` – jontro Dec 19 '17 at 02:22
  • 1
    I think Uint8Array would be faster - unless you were using the clamping features for graphics, which maybe faster in that case. – Tomachi Nov 02 '18 at 10:39
  • Neither the answer, nor the examples give a clue why and in what cases that behavior of `Uint8ClampedArray` could be beneficial. – Ilya Dec 18 '18 at 16:51
  • 10
    @llya These are for image/video/audio process. The main feature is: it never overflow/underflow. When you are trying to increase the brightness in an image: max brightness (255)+1 should give 255, not overflow to zero. – J-16 SDiZ Apr 04 '19 at 06:26