Canvas getImageData () For optimal performance. Pull all data or one at a time?

I need to scan every pixel in the canvas image and play a little with colors, etc. For optimal performance, should I capture all the data in one go and work on it through an array? Or should I name each pixel when I work on it.

So basically ...

data = context.getImageData(x, y, height, width);

VS

data = context.getImageData(x, y, 1, 1); //in a loop height*width times.
+4
source share
3 answers

, : a) () , . ) , DOM, . c) , ( ... ).

, .

Javascript Typed, imageData.

, , ( 2)):

?

( :)


UInt32Array ImageData :

var myGetImageData = myTempCanvas.getImageData(0,0,sizeX, sizeY);
var sourceBuffer32     = new Uint32Array(myGetImageData.data.buffer);

sourceBuffer32 [i] , , , 32- int . 0, , (!= (0,0,0,0))

Uint8Array:

var myGetImageData = myTempCanvas.getImageData(0,0,sizeX, sizeY);
var sourceBuffer8     = new Uint8Array(myGetImageData.data.buffer);

, R = G = B,

sourceBuffer8[4*i]>Threshold

i- , UInt32Array:

sourceBuffer32[i]=0xff000000;

/ :

sourceBuffer32[i]= (A<<24) | (B<<16) | (G<<8) | R ;

:

sourceBuffer32[i]= 0xff000000 | (B<<16) | (G<<8) | R ;

(, R ).


@Ken, , , , 32 . little-endian, RGBA ABGR 32 .
  , 32- , , , - - 32- Big endian. :

function isLittleEndian() {     
// from TooTallNate / endianness.js.   https://gist.github.com/TooTallNate/4750953
    var b = new ArrayBuffer(4);
    var a = new Uint32Array(b);
    var c = new Uint8Array(b);
    a[0] = 0xdeadbeef;
    if (c[0] == 0xef) { isLittleEndian = function() {return true }; return true; }
    if (c[0] == 0xde) { isLittleEndian = function() {return false }; return false; }
    throw new Error('unknown endianness');
}


function reverseUint32 (uint32) {
    var s32 = new Uint32Array(4);
    var s8 = new Uint8Array(s32.buffer);
    var t32 = new Uint32Array(4);
    var t8 = new Uint8Array(t32.buffer);        
    reverseUint32 = function (x) {
        s32[0] = x;
        t8[0] = s8[3];
        t8[1] = s8[2];
        t8[2] = s8[1];
        t8[3] = s8[0];
        return t32[0];
    }
    return reverseUint32(uint32);
};
+13

, GameAlchemist, , , DataView:

var data = context.getImageData(0, 0, canvas.width, canvas.height);
var view = new DataView(data.data.buffer);

// Read or set pixel (x,y) as #RRGGBBAA (big endian)
view.getUint32(4 * (x + y*canvas.width));
view.setUint32(4 * (x + y*canvas.width), 0xRRGGBBAA);

// Read or set pixel (x,y) as #AABBGGRR (little endian)
view.getUint32(4 * (x + y*canvas.width), true);
view.setUint32(4 * (x + y*canvas.width), 0xAABBGGRR, true);

// Save changes
ctx.putImageData(data, 0, 0);
+2

, , , .

, , , , .

, -. , , , .

getImageData() , , , .

+1

All Articles