Difference between Uint8Array and Uint8ClampedArray
Asked Answered
S

1

100

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?

Shier answered 17/2, 2014 at 2:47 Comment(0)
U
133

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
Underlaid answered 17/2, 2014 at 3:8 Comment(7)
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.Pepito
The OP mentioned this was used for pixel values in the canvas, is this a shortcut for saturated arithmetic?Insolvency
@Felix, So Uint8Array is more performant because no bounds checking need be done?Vince
Also ImageData is created from an Uint8ClampedArrayHoenir
I think Uint8Array would be faster - unless you were using the clamping features for graphics, which maybe faster in that case.Photometry
Neither the answer, nor the examples give a clue why and in what cases that behavior of Uint8ClampedArray could be beneficial.Embree
@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.Sibyl

© 2022 - 2024 — McMap. All rights reserved.