Add a paint bucket to an existing Fabric.js canvas

I wanted to add a paint bucket to a Fabric.js canvas so I could click inside an outline and fill it with color. I built fabricjs-floodfill and put together a coloring demo so you can try it before adding it to your own app.
Try the coloring demo · View the source on GitHub
Add it to your canvas
Copy floodfill.global.js from the repo. Load it after Fabric.js, then pass in your existing canvas instance.
<script src="./floodfill.global.js"></script> <script> const bucket = FabricFloodFill.createFloodFill(canvas, { ImageClass: fabric.FabricImage || fabric.Image }); canvas.on('mouse:down', ({ e }) => { if (e.button > 0) return; bucket.fillFromEvent(e, '#a78bfa'); }); </script> The bucket finds boundaries in what’s visible on the canvas, including images, shapes, and strokes. It adds each fill as a separate Fabric image, so the original objects stay editable. For outlines with small breaks, try passing { gapClose: 4 } as the third argument to fillFromEvent.
The browser test matrix covers Fabric.js 3.4.0, 4.6.0, 5.2.1, 6.9.1, and 7.4.0.
If you try it on your own artwork, I’d be curious to hear how it handles thin outlines or small gaps. Those are the cases I’d like to test with more real examples.
Coloring pages made with MockoFun Coloring Pages template.
原文:https://www.a8q9.cn/en/article/add-a-paint-bucket-to-an-existing-fabric-js-canvas-c98ae6.html