2015-09-24 64 views
0

enter image description hereJavaScript的畫布:如何獲得透明PNG文件的具體點?

好的,我感到困惑與獲取圖像數據的功能爲 https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData

我有一個路徑圖像,其與上述透明背景PNG格式。我需要得到的是位於高度/ 2的路徑左右兩邊的座標x,y。 (紅色箭頭的點)

getImageData是否使用正確的函數?任何人都可以就如何獲得它們提供一些建議嗎?

在此先感謝。

回答

2

是,使用getImageData(x, y, width, height);
在這種情況下,你只有兩種顏色(這裏透明&白色):

var img = new Image(); 
 
img.onload = getPoints; 
 
img.crossOrigin = 'anonymous'; 
 
img.src = "https://dl.dropboxusercontent.com/s/lvgvekzkyqkypos/path.png"; 
 

 
function getPoints(){ 
 
    // set our canvas 
 
    var canvas = document.createElement('canvas'), 
 
     ctx = canvas.getContext('2d'); 
 
    canvas.width = this.width; 
 
    canvas.height = this.height; 
 
    // draw the image 
 
    ctx.drawImage(this,0,0); 
 
    // get the middle y line 
 
    var imageData = ctx.getImageData(0,Math.floor(this.height/2), this.width, 1); 
 
    var data = imageData.data; 
 
    // set an empty object that will store our points 
 
    var pts = {x1: null, y1: Math.floor(this.height/2), x2: null, y2:Math.floor(this.height/2)}; 
 
    // define the first opacity value 
 
    var color = 0; 
 
    // iterate through the dataArray 
 
    for(var i=0; i<data.length; i+=4){ 
 
    // since we'relooking only for non-transparent pixels, we can check only for the 4th value of each pixel 
 
    if(data[i+3]!==color){ 
 
     // set our value to this new one 
 
     color = data[i+3]; 
 
     if(!pts.x1) 
 
     pts.x1 = i/4; 
 
     else 
 
     pts.x2 = i/4; 
 
     } 
 
    } 
 
    
 
    snippet.log('start points : '+pts.x1+'|'+pts.y1); 
 
    snippet.log('end points : '+pts.x2+'|'+pts.y2); 
 
    ctx.fillStyle = 'red'; 
 
    ctx.fillRect(pts.x1-5, pts.y1, 10, 10); 
 
    ctx.fillRect(pts.x2-5, pts.y2, 10, 10); 
 
    document.body.appendChild(canvas); 
 
    }
body{background-color: blue}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

+0

剛剛完成測試它。奇蹟般有效。然而,我仍然試圖理解你的代碼如何與透明的第四個值一起工作,爲什麼data [i + 3]並沒有遍歷每個數據。無論如何,謝謝你給我一個開始! – tipsywacky

+1

ctx.getImageData()確實會返回一個imageData對象。在這個對象中,有一個名爲'data'的屬性,它是一個ArrayBuffer。此ArrayBuffer包含每個像素的每個紅色,綠色,藍色和alpha(透明)值。因此,在這段代碼中,我正在迭代4個數據(每個像素)並只查找alpha值('data [i + 3]')。如果我必須檢查像素是否真的是白色的,我會完成if [data [i] === data [i + 1] === data [i + 2] === data [i + 3] === 255)' – Kaiido

+0

啊!疑難雜症!非常感謝!這很有趣,這是如何工作的。 – tipsywacky