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

Hey everyone,

I’m working on a drawing app using Fabric.js and I’m stuck on making a cool background grid. You know, like the one Miro has? It goes on forever and looks awesome!

Here’s what I want to do:

  1. Make the grid bigger or smaller when you zoom in or out
  2. Move the grid around when you pan the canvas
  3. Have the grid fit perfectly when you change the browser size

I’ve looked all over the place but can’t find anything that does all these things and works smoothly. If anyone has tips or knows how to do this, I’d be super grateful!

Thanks a bunch for any help you can give me. I’m really excited to get this working!

I’ve implemented something similar using Fabric.js. The key is to create a custom grid object that extends the Fabric.Group class. This allows you to manipulate the grid as a single entity.

For infinite panning, you can use the ‘object:moving’ event to detect canvas movement and redraw the grid accordingly. Zooming can be handled by scaling the grid object and adjusting line thickness.

To ensure responsiveness, listen for window resize events and update the grid dimensions. You might also want to use requestAnimationFrame for smooth rendering during pan and zoom operations.

One optimization tip: only draw visible grid lines to improve performance on larger canvases. This approach has worked well in my projects, providing a smooth, Miro-like experience.

I’ve actually tackled a similar challenge in one of my projects. The key is to create a separate canvas layer for the grid and update it dynamically based on zoom level and pan position.

Here’s what worked for me:

  1. Create a background canvas that’s slightly larger than the viewport.
  2. Use requestAnimationFrame to continuously redraw the grid.
  3. Calculate grid spacing based on zoom level.
  4. Offset the grid drawing based on pan position.
  5. Adjust the background canvas size on window resize.

The tricky part was optimizing performance. I ended up using a Web Worker to handle grid calculations off the main thread, which really smoothed things out.

One gotcha to watch for: make sure your grid lines align perfectly at integer zoom levels to avoid visual artifacts.

Hope this helps point you in the right direction! Let me know if you need any clarification on the approach.