簡體   English   中英

確定Javascript中黑白像素之間的距離

[英]Determine the distance between black and white pixels in Javascript

我正在計划為此項目使用JavaScript(但我願意使用其他東西)。 我在javascript中加載圖像,當我在圖像上放置一個點時,我想計算從放置點到第一個黑色或灰色像素的x和y距離。

范例圖片

因此,我將紅點放置在圖像上,然后向用戶顯示從選定點到第一個黑色像素的x,y距離。 距離可以以像素為單位(我不介意)。 這可能嗎,有人可以幫助我嗎?

謝謝!

您可以使用該MDN示例中所示的 drawImage將圖像繪制到畫布上 然后,使用getImageData提取像素數據,該方法返回一個包含widthheightdata屬性的對象。

data屬性是每行像素從左到右排列的一系列rgba(紅色,綠色,藍色,alpha)值。 值介於0-255之間。 對於透明度,0表示像素是透明的,255表示不透明。

該數組如下所示:

    ,--- first pixel (top left)
    |       ,-- second pixel
____|___ ___|___    _______,--- last pixel (bottom right)
[r,g,b,a,r,g,b,a...,r,g,b,a]

給定畫布上下文的寬度和高度,您可以使用一些不太復雜的數學來獲得像素為(x,y)或僅通過一些嵌套循環運行,就可以找到任意給定(x,y)的像素。

至於尋找最接近的黑色像素,建議您從像素(x,y)開始,然后遞增/遞減x,y或兩者兼而有之,以獲取周圍的像素。 我能想到的最快方法是沿一個方向穿過像素,直到碰到想要的像素。 為其他方向執行此操作。 然后比較值。

在笛卡爾平面中使相鄰像素距離“紅色像素” 1個像素的示例。 如果只需要水平和垂直,則可以省略對角線。

/*(x-1,y+1)*/ ( x ,y+1) /*(x+1,y+1)*/
  (x-1, y )   ( x , y )   (x+1, y )
/*(x-1,y-1)*/ ( x ,y-1) /*(x+1,y-1)*/

對於距離,給定“紅色像素”(x,y)和最接近的黑色像素(x,y),您可以使用許多距離公式之一

執行此操作的另一種方法是按照Dreamer的建議@Joseph再次使用getImageData函數,但可以在以下位置進行搜索而不是按方向搜索:

// the context to the canvas which holds your map
var ctx {...};

var point = {x:x, y:y};
// this gets a 3 by 3 bitmap data from your canvas with the centre being your point
var search = ctx.getImageData(x - 1, y - 1, 3, 3);

var match = false;
while(!match)
{
    // iterate over the search array looking for a black or grey pixel
    // and add the co ordinates of the matches into another array

    // if we found matches in this loop, calculate the shortest length match
    // and then break out of the loop

    // otherwise get a bigger sample data to search through and do this loop again
    // you could optimise this by skipping the pixels you looked through
    // in the previous loop
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM