18

How can I convert a Uint8ClampedArray (like one used for storing HTML5 canvas image data) to a regular array, in which values won't be constrained to 0-255?

Austin Greco
  • 32,997
  • 6
  • 55
  • 59
cincplug
  • 1,024
  • 5
  • 20
  • 38
  • You can't, at least not if you intend to keep the images ? – adeneo Apr 24 '15 at 12:54
  • Sorry, I wasn't clear enough. I need to copy Uint8ClampedArray's array data into another array, which would be regular array. Then, when I need to, for example, adjust brightness of image, I could manipulate regular array's data and copy that data back to clamped array. Otherwise, if I manipulate clamped array directly, I am getting pixels 'burned'. – cincplug Apr 24 '15 at 12:58
  • I wouldn't think that was doable, but I really have no idea. If you can't store the images from the canvas in a regular array to begin with because it's binary, you probably can't copy that data to a regular array either. – adeneo Apr 24 '15 at 13:01
  • Well the only way I found was to simply declare an empty array and to push all the data from clamped array into it. Even slice() didn't work, because it is very little supported accross browsers for Uint arrays. Thanks anyway. – cincplug Apr 24 '15 at 14:37

1 Answers1

29

You can convert a typed array to a regular array by using Array.prototype.slice

var typedArray = new Uint8ClampedArray([1, 2, 3, 4]);
var normalArray = Array.prototype.slice.call(typedArray);

Also if using ES6 you may be able to use Array.from instead:

var normalArray = Array.from(typedArray);

See MDN - JavaScript typed arrays

Austin Greco
  • 32,997
  • 6
  • 55
  • 59