如何在FabricJS中检测画布上的空白区域?

时间:2016-03-21 05:05:04

标签: javascript jquery canvas html5-canvas fabricjs

我需要检查FabricJS中画布上是否有空白区域并显示警告。我认为这可以通过检测画布上的像素来完成,但我不知道。怎么做?

1 个答案:

答案 0 :(得分:2)

要获取pixeldata,您需要访问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个字节,红色,绿色,蓝色和alpha各一个字节。

获得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获取像素以及如何获取像素地址(索引)。