Creating an endless background grid in Fabric.js canvas, similar to Miro

Hey everyone,

I’m working on a drawing tool using Fabric.js and I’m stuck on how to make an infinite background grid that works like Miro’s. Here’s what I’m trying to achieve:

  1. The grid should adjust when zooming in or out
  2. Panning should move the grid accordingly
  3. The grid should adapt to canvas size changes when the browser window is resized

I’ve looked around and found some examples, but they either don’t include zooming and panning or have performance issues. Has anyone tackled this before? Any tips or suggestions would be super helpful!

I’m really excited about this project and would love to hear your thoughts. Thanks in advance for any advice you can share!

I’ve implemented a similar feature in a project recently. One approach that worked well was creating a separate canvas layer for the grid beneath the main Fabric.js canvas. This allows for efficient rendering and updates.

For zooming and panning, you can use Fabric.js’s built-in viewportTransform property. Adjust the grid’s scale and position based on these values. To handle resizing, listen for window resize events and update the grid canvas dimensions accordingly.

For performance, consider only drawing visible grid lines within the viewport. You can calculate this based on the current view and zoom level. Also, use integer pixel values for line positions to avoid anti-aliasing issues.

Hope this helps point you in the right direction!

I’ve actually dealt with this exact issue in a project I worked on last year. One trick that really helped was using SVG patterns for the grid instead of drawing it manually. It’s surprisingly efficient and scales beautifully with zooming.

Here’s what I did: I created a small SVG pattern for the grid and set it as the background of a div that sits behind the Fabric.js canvas. Then, I synced the div’s transform with the canvas’s viewportTransform. This way, the grid moves and scales automatically with panning and zooming.

For resizing, I just adjusted the div’s size to match the canvas. The SVG pattern takes care of filling the space seamlessly.

This approach was much smoother than redrawing the grid constantly, especially on lower-end devices. Give it a shot and see if it works for your use case!

hey mate, ive tackled something similar before. have u tried using a custom render function? u can draw the grid dynamically based on zoom and pan. use requestAnimationFrame for smooth updates. also, consider caching grid sections for better performance. good luck with ur project!