开发者

How to get pixel coordinates of a pixel inside an html5 canvas

开发者 https://www.devze.com 2023-02-23 00:52 出处:网络
I 开发者_运维百科know that you can get the value of each pixel inside the html5 Canvas using getImageData() and .data() but is there a way to get their coordinates and not just their values?var w = ct

I 开发者_运维百科know that you can get the value of each pixel inside the html5 Canvas using getImageData() and .data() but is there a way to get their coordinates and not just their values?


var w = ctx.canvas.width, h = ctx.canvas.height;
var id = ctx.getImageData(0,0,w,h);
var d = id.data;
for (var y=0;y<h;++y){
  for (var x=0;x<w;++x){
    var i=(y*w+x)*4;
    var r=d[i],g=d[i+1],b=d[i+2],a=d[i+3];
  }
}

It's just as easy to derive the x/y from the index while looping through the image data array, or to add in offsets if you have fetched only part of the canvas pixels.

for (var i=0,len=d.length;i<len;i+=4){
  var x=i/4%w,y=(i/4-x)/w;
  var r=d[i],g=d[i+1],b=d[i+2],a=d[i+3];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号