2016-03-21 47 views
1

我需要檢查FabricJS的畫布上是否有空白區域並顯示警報。我認爲這可以通過在畫布上檢測像素來完成,但我不知道。怎麼做?如何在FabricJS上檢測畫布上的空白區域?

+0

在你的問題中沒有太多細節。 FabricJS不提供爲像你自己的html5 canvas一樣的'getImageData'獲取像素信息。您可能必須獲取對您的基礎FabricJS畫布(這是一個本機html5畫布)的引用,然後執行.getImageData。 – markE

回答

2

要獲得像素數據,您需要訪問2D上下文。要在FabricJS中做到這一點,您必須致電StaticCanvas.getContext();標準織物畫布將在原型鏈中具有此功能。 Fabric StaticCanvas doc

從那裏得到的像素數據使用

var ctx = yourCanvas.getContext(); // your canvas is the Fabric canvas 
var pixelData = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height); 

要訪問您要計算指數,然後檢索的4個字節,使像素,一個字節分別處理紅,綠單個像素,藍色和阿爾法。

函數獲取一個像素,一旦你有pixelData。

// pixelData is the pixel data, x and y are the pixel location 
function getPixel(pixelData,x,y){ 
    // make sure the coordinate is in bounds 
    if(x < 0 || x >= pixelData.width || y < 0 || y >= pixelData.height){ 
     return { 
      r : 0, 
      g : 0, 
      b : 0, 
      a : 0 
     }; 
    } 
    // get the index of the pixel. Floor the x and y just in case they are not ints 
    var index = Math.floor(x) * 4 + Math.floor(y) * 4 * pixelData.width; 
    // return the pixel data 
    return { 
     r : pixelData.data[index++], 
     g : pixelData.data[index++], 
     b : pixelData.data[index++], 
     a : pixelData.data[index++] 
    }; 
} 

這應該有助於您找到空白區域。請注意,當alpha爲零時,紅色,綠色和藍色也將爲零。上面的函數非常慢,因此它不適用於您的問題,它只是顯示如何從pixelData中獲取像素以及如何獲取像素地址(索引)。

+1

@MarkE我只是在firefox,chrome和edge上嘗試過它,然後渲染'rgba = 0xffffffff'然後'comp =「xor」'然後繪製一個全白的圖像並讀取相同的像素我得到'rgba = 0x00000000'從內存標準要求零阿爾法與所有其他通道的零匹配。 – Blindman67

+0

好的,我可能記得錯了......在這方面,我可以發誓一陣子XOR咬我。感謝您檢查:-) – markE