Skip to content

Instantly share code, notes, and snippets.

@gengkev
Created April 3, 2012 20:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gengkev/2295355 to your computer and use it in GitHub Desktop.
Save gengkev/2295355 to your computer and use it in GitHub Desktop.
Uint8ClampedArray shim
if (!window.Uint8ClampedArray && window.Uint8Array && window.ImageData) {
window.Uint8ClampedArray = function(input,arg1,arg2) {
var len = 0;
if (typeof input == "undefined") { }
else if (!isNaN(parseInt(input.length))) { //an array, yay
len = input.length;
}
else if (input instanceof ArrayBuffer) {
return new Uint8ClampedArray(new Uint8Array(input,arg1,arg2));
}
else {
len = parseInt(input);
if (isNaN(len) || len < 0) {
throw new RangeError();
}
input = undefined;
}
len = Math.ceil(len / 4);
if (len == 0) len = 1;
var array = document.createElement("canvas")
.getContext("2d")
.createImageData(len, 1)
.data;
if (typeof input != "undefined") {
for (var i=0;i<input.length;i++) {
array[i] = input[i];
}
}
try {
Object.defineProperty(array,"buffer",{
get: function() {
return new Uint8Array(this).buffer;
}
});
} catch(e) { try {
array.__defineGetter__("buffer",function() {
return new Uint8Array(this).buffer;
});
} catch(e) {} }
return array;
}
}
@gengkev
Copy link
Author

gengkev commented Apr 3, 2012

This is pretty silly. It works by creating a with a specified width/height and calling its getImageData to return a CanvasPixelArray for you to use; it's obviously a better idea to just use a Uint8Array and watch what values you put in it, but I need this for Opera compatibility since you can only give putImageData either a Uint8ClampedArray or a CanvasPixelArray, which has no constructor and can't be instantiated any other way, so that's pretty much the only use case you'd need this for.

I like how long that sentence was!

@gengkev
Copy link
Author

gengkev commented Apr 3, 2012

oh btw, it also tries to define a getter for the buffer property on the array, but if that's not possible you'll have to calculate it yourself.

@p01
Copy link

p01 commented Jun 24, 2014

FWIW prior to version 12, the CanvasPixelArray in Opera was not clamped but clipped.

@andyearnshaw
Copy link

Sadly, this is only any good for the native clamping support. The buffer property is pretty much useless because CanvasPixelArray doesn't implement the ArrayBufferView interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment