Skip to content

Instantly share code, notes, and snippets.

@gengkev
Created April 3, 2012 20:45
Show Gist options
  • Select an option

  • Save gengkev/2295355 to your computer and use it in GitHub Desktop.

Select an option

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

gengkev commented Apr 3, 2012

Copy link
Copy Markdown
Author

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

p01 commented Jun 24, 2014

Copy link
Copy Markdown

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

@andyearnshaw

Copy link
Copy Markdown

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