Gordo
Gordo

Reputation: 789

How can a get a rectanglular portion of canvas ImageData from the cached pixeldata of the whole image?

Using ctx.getImageData(x, y, w, h) it is possible to retrieve the pixeldata of a rectangular portion of an image;

However I need to perform a lot of checks on various portions of the data. Extracting the imagedata each time is expensive. Therefore I would like to cache the whole canvas imagedata, and have a function return the pixels of a given rectangle within that cached data.

In other words, if I have retrieved the imagedata of the whole canvas in advance and cached it to a variable, how can I then extract a rectangular portion of the pixeldata from this cache?

Any help would be greatly appreciated.

Upvotes: 1

Views: 663

Answers (1)

user1693593
user1693593

Reputation:

Here is one way to parse a region of a larger bitmap array [rx, ry, rwidth, rheight],:

for(var y = ry; ry < (ry + rheight); y++) {
    for(var x = rx; x < (rx + rwidth); x++) {

        var pos = (y * width + x) * 4;  /// for byte arrays
        var pos =  y * width + x;       /// for Uint32 arrays
    }
}

pos being the position in the array. If you don't need to check individual components (or you can use a static 32-bit value for comparison) I would recommend you to use an Uint32Array view on the buffer which is much faster than iterating a byte array.

However, to extract the region is probably slower than using getImageData() as you would need to use JS to iterate as above to get the region, then iterate again parsing the data using JS.

Upvotes: 1

Related Questions