画布 - 获取颜色的位置(如果可用)

iCo*_*nor 5 html javascript canvas

是否可以获取画布上颜色的位置。

我知道你可以在这样的位置获得颜色

context.getImageData( arguments ).data
Run Code Online (Sandbox Code Playgroud)

但我想尝试在画布上找到一种颜色,所以说我会选择黑色。

rgb(0, 0, 0);
Run Code Online (Sandbox Code Playgroud)

我想获得该颜色的位置(如果它存在于画布上),我已经询问了 Google,但我只在与我需要的位置相反的位置获得获取颜色。

小智 4

正如已经提到的,您需要迭代像素缓冲区。

这是一种方法:

在线演示在这里

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;
}
Run Code Online (Sandbox Code Playgroud)

这将返回您给定颜色的第一个匹配的 x/y 位置 ( color = [r, g, b])。如果未找到颜色,则函数返回null

(代码可以通过多种方式进行优化,我在这里没有解决这个问题)。