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
Answer from Felix Kling on Stack OverflowI think you shouldn't be using Uint8Array to store your data - it simply doesn't work like a Uint8ClampedArray. For example:
a = new Uint8Array(1);
b = new Uint8ClampedArray(1);
a[0] = 256;
b[0] = 256;
a[0] === 0; // true
b[0] === 255; // true
I would just use a regular array (if that's an option) and clamp the values when you store them into it, or when you read them to generate your string like this:
s += String.fromCharCode(Math.max(0, Math.min(255, array[i])));
The WhatWG has recommended the Uint8ClampedArray for storing canvas pixel data.
But, various browsers use Uint8ClampedArray (or not) depending on whether they've implemented the WhatWG recommendations.
Therefore, a more cross-browser solution is to pull an array from your canvas using .getImageData and then manipulate that array as desired. That way you know you're using a compatible array.
var imageData = context.getImageData(0,0,canvas.width,canvas.height);
var data = imageData.data; // this array is always compatible with its browser.