Created
April 3, 2012 20:45
-
-
Save gengkev/2295355 to your computer and use it in GitHub Desktop.
Uint8ClampedArray shim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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.
FWIW prior to version 12, the CanvasPixelArray in Opera was not clamped but clipped.
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
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!