How to get pixel coordinates from canvas polygon (

2019-07-21 15:58发布

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条回答
Lonely孤独者°
2楼-- · 2019-07-21 16:28

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);
    }
  }
查看更多
登录 后发表回答