如何在 FabricJS 中检测 canvas 上的空白区域?
How to detect empty areas on canvas in FabricJS?
我需要检查 FabricJS 中 canvas 上是否有任何空白区域并显示警报。我认为这可以通过检测 canvas 上的像素来完成,但我不知道。怎么做?
要获取像素数据,您需要访问 2D 上下文。要在 FabricJS 中做到这一点,你必须调用 StaticCanvas.getContext();
标准结构 canvas 将在原型链中包含它。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 中获取像素以及如何获取像素地址(索引)。
如果你想跟踪空白区域的点击,你可以勾选event.subTargets
canvas.on('mouse:down', (e) => {
if (!event.subTargets.length) {
//do stuff...
}
})
我需要检查 FabricJS 中 canvas 上是否有任何空白区域并显示警报。我认为这可以通过检测 canvas 上的像素来完成,但我不知道。怎么做?
要获取像素数据,您需要访问 2D 上下文。要在 FabricJS 中做到这一点,你必须调用 StaticCanvas.getContext();
标准结构 canvas 将在原型链中包含它。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 中获取像素以及如何获取像素地址(索引)。
如果你想跟踪空白区域的点击,你可以勾选event.subTargets
canvas.on('mouse:down', (e) => {
if (!event.subTargets.length) {
//do stuff...
}
})