2013-04-17 139 views
1

我打算在此項目中使用JavaScript(但我願意使用其他內容)。我在javascript中加載圖像,當我在圖像上放置一個點時,我想計算從放置點到第一個黑色或灰色像素的x和y距離。確定Javascript中黑色和白色像素之間的距離

Example Image

所以我把圖片上的紅點,然後我想顯示用戶在x,y距離所選擇的點到第一黑色像素。距離可以像素(我不介意)。這是可能的,任何人都可以幫助我嗎?

謝謝!

回答

1

可以通過使用drawImage如本MDN example.看出然後通過使用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),就可以使用one of many distance formulas

+0

感謝您的回答,你就知道一個庫或其他東西自動執行此操作? – DanFritz

1

另一種方式做,這將是再次使用getImageData功能@Joseph夢想家建議,但不是在方向搜索的內容,你可以做的是以下幾點:

// 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 
} 
+0

感謝您的建議! – DanFritz

相關問題