【问题标题】:How to detect empty areas on canvas in FabricJS?如何在 FabricJS 中检测画布上的空白区域?
【发布时间】:2016-07-07 12:24:54
【问题描述】:

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

【问题讨论】:

  • 您的问题没有太多细节。 FabricJS 不像原生 html5 画布使用 getImageData 那样为您获取像素信息。您可能需要获取对底层 FabricJS 画布(本机 html5 画布)的引用,然后执行 .getImageData。

标签: javascript jquery canvas html5-canvas fabricjs


【解决方案1】:

要获取像素数据,您需要访问 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 获取像素以及如何获取像素地址(索引)。

【讨论】:

  • @MarkE 我刚刚在 firefox、chrome 和 edge 上尝试过,然后渲染 rgba = 0xffffffff 然后 comp = "xor" 然后绘制一个全白图像并读取相同的像素我得到 rgba = 0x00000000 从内存标准要求零 alpha 与所有其他通道的零匹配。
  • 好吧,我可能记错了......我可以发誓不久前在这方面 XOR 咬了我。感谢您检查:-)
【解决方案2】:

如果你想跟踪空白区域的点击,你可以检查 event.subTargets

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

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多