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

How to detect empty areas on canvas in FabricJS?

本文关键字:空白 区域 检测 FabricJS      更新时间:2023-09-26

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

要获取像素数据,您需要访问 2D 上下文。要在 FabricJS 中做到这一点,你必须调用标准织物画布StaticCanvas.getContext();在原型链中会有这个。织物静态画布文档

从那里获取像素数据使用

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 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 为零时,红色、绿色和蓝色也将为零。上面的函数非常慢,所以它不适合在你的问题中使用,它只是显示如何从像素数据中获取像素以及如何获取像素地址(索引)。

如果你想

跟踪点击一个空白区域,你可以检查event.subTargets

canvas.on('mouse:down', (e) => {
  if (!event.subTargets.length) {
    //do stuff... 
  }
})