Canvas Javascript Floodfill Algorithm Left White Pixels Without Color
I have been working on a drawing app like paint. I am in the part of the floodfill and I am using and algorithm that I found on internet, however, it left some white pixels near th
Solution 1:
The reason is that when you draw on a canvas, some anti-aliasing is applied, which involves colour-gradients.
Instead of comparing with ===
, you could allow some tolerance. You could for instance use this formula:
constcolorDiff = (a, b) => a === b ? 0// quick exit
: ((a & 0xFF) - (b & 0xFF)) ** 2
+ (((a >> 8) & 0xFF) - ((b >> 8) & 0xFF)) ** 2
+ (((a >> 16) & 0xFF) - ((b >> 16) & 0xFF)) ** 2;
NB: this assumes that the alpha value is 255 (opaque).
Then in your code choose some value for a tolerance
, between 0 and 100000, for example 1000, and replace:
if (currentColor === targetColor) {
with:
if (colorDiff(currentColor, targetColor) <= tolerance) {
Post a Comment for "Canvas Javascript Floodfill Algorithm Left White Pixels Without Color"