How to get pixel coordinates from canvas polygon (filled area)

左心房为你撑大大i 提交于 2019-12-24 03:29:51

问题


I am creating an interface that enables user to hightlight custom area in map with overlay canvas polygons. as in figure. then, I want to get all filled pixels from canvas with specified color so that I can transform that pixel values into geo LAT-LONG values. I want to create custom database that hold LAT-LONG values ranges with tagged custom known names. It's ok to create overlay canvas polygons by mouse-dragging. But I have a problem in retrieving filled area from canvas as pixel array. I found that

var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
var data=image.data;  

But,it's impossible to iterate all value and cast related R,G,B values and validate with specified color for entire image data. Instead, is there any way to get image data as pixels only for filled area of polygon and let me know other solutions for this purpose if any? ![enter image description here][1] Please help me.


回答1:


What you need is reverse processing. You can simply iterate canvas and create index and related RGBA values by following formula and compare with filled color.

var index = (x + y * imageData.width) * 4;   

sample execution is as follow:

var imageData = ctx.getImageData(0, 0,canvas.width, canvas.height);
  var data = imageData.data;
  var filled=[];
  for(var x=0;x<canvas.width;x++){
  for(var y=0;y<canvas.height;y++){
    var index = (x + y * imageData.width) * 4;

    if(data[index+0]==colorToCheck.R && data[index+1]==colorToCheck.G && data[index+2]==colorToCheck.B && data[index+3]==colorToCheck.A){
        var cx={"X":x,"Y":y}; //
        filled.push(cx);
    }
  }


来源:https://stackoverflow.com/questions/28536987/how-to-get-pixel-coordinates-from-canvas-polygon-filled-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!