javascript - 如何在 FabricJS 中检测 Canvas 上的空白区域?

标签 javascript jquery canvas html5-canvas fabricjs

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

最佳答案

要获取像素数据,您需要访问 2D 上下文。要在 FabricJS 中执行此操作,您必须调用 StaticCanvas.getContext(); 标准织物 Canvas 将在原型(prototype)链中包含此内容。 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 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 获取像素以及如何获取像素地址(索引)。

关于javascript - 如何在 FabricJS 中检测 Canvas 上的空白区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36123507/

相关文章:

javascript - 如何完善这个 JS 数组搜索功能?

javascript - 如何在单击按钮时将第一个字母设置为大写

javascript - JS/jQuery > 在附加输入中突出显示文本

canvas - 使用 canvas 和 setDragImage 创建动态拖动图像

HTML5 Canvas 元素样式?

javascript - 嵌套 ng-repeat 中的单选按钮

javascript - 如何在 Angularjs Protractor 中使用命令行参数?

javascript - 如何在使用 JavaScript 打字时动态关闭括号?

javascript - 我可以使用哪些 JavaScript 函数来检查电子邮件和电话号码是否有效,而无需借助 jquery 插件?

javascript - canvas 2d Context.translate(...) 是如何工作的?