简体   繁体   中英

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

I want to draw a matrix on a html5 canvas with image. For example the matrix will be like below:

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

I want to detect a particular color on the canvas, say "red". All the pixels where red color is there the matrix value will be "1", every other color it will be "0". Is this practically possible?

  1. Can we draw matrix on image canvas?
  2. Can we detect color and set/update matrix value?

This is to use with 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 similar to this, but can't make out how its done.

Have you tried 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

Edit

For example, if your 'red' color is defined as [255, 0, 0, 255] your matrix can be obtained in this way:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM