I'm working on this real head scratcher!
I'm successfully adding byte values to a Uint8ClampedArray and using the array to generate a byte string using this function:
this.utf8ArrayToStr = function(array) {
var s = '';
for (var i = 0; i < array.length; i++) {
s += String.fromCharCode(array[i]);
}
return s;
};
This works a treat and successfully generates the correct byte sequence.
The problem is that not all browsers support Uint8ClampedArray and I specifically need it to work on Android browsers.
I tried using a standard Uint8Array but it results in extra byte values in the resulting string, causing erroneous behaviour.
I also found a small shim here, but it did not work, again producing extra output: https://gist.github.com/gengkev/2295355
Is there anyway I could make Uint8Array act as Uint8ClampedArray, or more specifically, clamp the values while generating the string in the function above?
UPDATE: It looks like I'm getting somewhere using an standard array but there's still some messed up characters causing problems.
I 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.