用图像在 html5 canvas 上绘制矩阵并检测特定颜色

Draw a matrix on html5 canvas with image and detecting certain color

我想在带图像的 html5 canvas 上绘制矩阵。例如,矩阵如下所示:

var matrix = [
    [0, 0, 0, 1, 0],
    [1, 0, 0, 0, 1],
    [0, 0, 1, 0, 0],
];

我想检测 canvas 上的特定颜色,比如 "red"。红色所在的所有像素矩阵值将为“1”,所有其他颜色将为“0”。这实际上可能吗?

  1. 我们可以在图像上绘制矩阵吗canvas?
  2. 我们可以检测颜色和 set/update 矩阵值吗?

这个是和this js library.I am trying to build a small indoor assistance system, where in a user can navigate from one point to other with this. I saw an example一起使用的,和这个类似,但是不知道是怎么做到的。

你试过了吗getImageData

To obtain an ImageData object containing a copy of the pixel data for a canvas context, you can use the getImageData() method:

var myImageData = ctx.getImageData(left, top, width, height);

This method returns an ImageData object representing the pixel data for the area of the canvas whose corners are represented by the points (left,top), (left+width, top), (left, top+height), and (left+width, top+height). The coordinates are specified in canvas coordinate space units.

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas

编辑

比如你的'red'颜色定义为[255,0,0,255]你的矩阵可以这样得到:

var img = new Image();
img.src="http://example.com/image.png";
img.onload = function() {
  var matrix = detect(this, img.width, img.height);
  console.log(matrix);
};

function detect(img, width, height) {

    var matrix = [],
        canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');

    ctx.drawImage(img, 0, 0, width, height);

    for(var i = 0; i < width; i++){
        matrix[i] = [];
        for(var j = 0; j < height; j++){
            var imageData = ctx.getImageData(i, j, 1, 1);
            var data = imageData.data;
            matrix[i][j] = (data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255) ? 1 : 0; 
        }
    }
    return matrix;
}