Reputation: 3565
I need to check is there any empty areas on canvas in FabricJS and display alert. I think this can be done by detecting pixels on canvas but I have no idea. How to do that?
Upvotes: 1
Views: 1307
Reputation: 1
In case if you wanna track click on an empty area, you can check event.subTargets
canvas.on('mouse:down', (e) => {
if (!event.subTargets.length) {
//do stuff...
}
})
Upvotes: 0
Reputation: 54099
To get pixeldata you need access to the 2D context. To do that in FabricJS you have to call StaticCanvas.getContext();
the standard fabric canvas will have this in the prototype chain.Fabric StaticCanvas doc
From there to get the pixel data use
var ctx = yourCanvas.getContext(); // your canvas is the Fabric canvas
var pixelData = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height);
To access a single pixel you have to calculate the index and then retrieve the 4 bytes that make a pixel, one byte each for red, green, blue, and alpha.
Function to get a pixel once you have the 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++]
};
}
That should help you find the empty areas. Note that when alpha is zero, red, green, and blue will also be zero. The function above is very slow so it is not intended for use in your problem, it just shows how to get a pixel from the pixelData and how to get a pixel address (index).
Upvotes: 2