2016-03-21 49 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