我想在 html5 Canvas 上用图像绘制一个矩阵。例如,矩阵如下所示:
var matrix = [
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
];
我想检测 Canvas 上的特定颜色,例如“红色”。所有红色像素的矩阵值都将为“1”,其他颜色的矩阵值为“0”。这实际上可能吗?
- 我们可以在图像 Canvas 上绘制矩阵吗?
- 我们可以检测颜色并设置/更新矩阵值吗?
这与 this js library 一起使用我正在尝试构建一个小型室内辅助系统,用户可以用它从一个点导航到另一个点。我看到一个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
编辑
例如,如果您的“红色”颜色定义为 [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;
}
关于javascript - 在html5 Canvas 上用图像绘制矩阵并检测特定颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29975694/