iConnor
iConnor

Reputation: 20189

Canvas - Get position of colour if available

Is it possible to get the position of a colour on canvas.

I know you can get the colour at a position like this

context.getImageData( arguments ).data

But I would like to try and find a colour in canvas, so say I would have this colour black.

rgb(0, 0, 0);

I would like to get the position of that colour if it exists on canvas, I've asked Google but I only get the Get colour at position which is the opposite of what I need.

Upvotes: 5

Views: 1959

Answers (2)

user1693593
user1693593

Reputation:

As mentioned already you need to iterate over the pixel buffer.

Here is one way you can do it:

(Online demo here)

function getPositionFromColor(ctx, color) {

    var w = ctx.canvas.width,
        h = ctx.canvas.height,
        data = ctx.getImageData(0, 0, w, h), /// get image data
        buffer = data.data,                  /// and its pixel buffer
        len = buffer.length,                 /// cache length
        x, y = 0, p, px;                     /// for iterating

    /// iterating x/y instead of forward to get position the easy way
    for(;y < h; y++) {

        /// common value for all x
        p = y * 4 * w;

        for(x = 0; x < w; x++) {

            /// next pixel (skipping 4 bytes as each pixel is RGBA bytes)
            px = p + x * 4;

            /// if red component match check the others
            if (buffer[px] === color[0]) {
                if (buffer[px + 1] === color[1] &&
                    buffer[px + 2] === color[2]) {

                    return [x, y];
                }
            }
        }
    }
    return null;
}

This will return the x/y position of the first match of the color you give (color = [r, g, b]). If color is not found the function returns null.

(the code can be optimized in various ways by I haven't addressed that here).

Upvotes: 4

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

You would need to iterate over the data property and check the RGB values. Basically you would iterate in groups of 4, as each pixel is stored as 4 indices, and compare the values accordingly.

Upvotes: 3

Related Questions