DEV Community

Cover image for Fabric.js 7 + React 19: six things that break, and how I fixed them
Debojit Saha
Debojit Saha

Posted on Edited on

Fabric.js 7 + React 19: six things that break, and how I fixed them

I build canvas editors at my day job. Most free React and Fabric.js starters online were written for Fabric v5 or v6, and they break on v7, which changed some defaults and removed a few methods the old code relies on. Below are six things that broke for me while building on Fabric 7 with React 19, and the fix for each one.

The canvas gets created twice

React 19 in StrictMode mounts every effect, cleans it up, and mounts it again in development. A naive effect creates a second Canvas on the same element, or disposes the one that is still live. What you see is stacked canvas layers, or a blank editor after the second mount, and it only happens in development, so it is easy to miss until a bug report arrives.

The fix is to keep the instance in a ref, create it only when the ref is empty, and dispose it in the cleanup so the second mount starts from nothing.

import { useEffect, useRef, type RefObject } from 'react';
import { Canvas } from 'fabric';

export function useFabricCanvas(elRef: RefObject<HTMLCanvasElement | null>) {
  const canvasRef = useRef<Canvas | null>(null);

  useEffect(() => {
    const el = elRef.current;
    if (!el || canvasRef.current) return; // guard: never attach a second Canvas

    canvasRef.current = new Canvas(el, { width: 800, height: 600 });
    return () => {
      void canvasRef.current?.dispose(); // StrictMode runs this before remounting
      canvasRef.current = null;
    };
  }, [elRef]);

  return canvasRef;
}
Enter fullscreen mode Exit fullscreen mode

Saved JSON loses your custom properties

toObject() writes the built-in properties and leaves out anything you attached yourself. A custom id or name set on an object is gone after a save and load, and any code that looks objects up by those fields then finds nothing. Scene files also outlive the code that reads them, so the format needs a version and a validator.

Pass the custom properties explicitly, stamp a schema version on the file, and parse it with Zod on load. When the version changes, a migration function upgrades the old shape first, so older files still open, and a broken file fails with a readable Zod error instead of a half-loaded canvas.

import { z } from 'zod';
import type { Canvas } from 'fabric';

const SCHEMA_VERSION = 1;

const SceneSchema = z.looseObject({
  schemaVersion: z.literal(SCHEMA_VERSION),
  objects: z.array(z.looseObject({ type: z.string() })),
});

export function saveScene(canvas: Canvas): string {
  const { objects } = canvas.toObject(['id', 'name']);
  return JSON.stringify({ schemaVersion: SCHEMA_VERSION, objects });
}

export function parseScene(raw: string) {
  return SceneSchema.parse(JSON.parse(raw)); // throws on bad input
}
Enter fullscreen mode Exit fullscreen mode

I use schemaVersion rather than version because Fabric already writes its own version field into the JSON, and two fields with the same name are a bad time.

Undo and redo

Undo sounds simple until you build it. There are two common approaches. Snapshots store the whole scene after each change, which is easy to get right. Commands store how to reverse each action, which keeps the history small but means every action needs an inverse. Either way, a single drag fires many move events, so the history needs grouped steps. Without grouping, one undo removes one pixel of movement and the user gives up.

I left this out of Lite. It takes more care than the rest of the starter, and it deserves its own section rather than a paragraph at the end of a list.

Exporting a canvas with an outside image

Draw an image from another origin onto a canvas and the canvas becomes tainted. Calling toDataURL on it then throws a security error, so PNG export simply stops working, usually with a message that points nowhere useful. The way around it is to load the image with a CORS request before adding it to the canvas. The image host has to send CORS headers for that to work. If it does not, the load fails, and you can show the user a clear message at that point instead of at export time.

Export also needs the artboard bounds, so the crop happens in the export options and not in the viewport.

import { FabricImage, type Canvas } from 'fabric';

type Bounds = { left: number; top: number; width: number; height: number };

export async function addImageFromUrl(canvas: Canvas, url: string) {
  const img = await FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
  canvas.add(img);
  canvas.requestRenderAll();
}

export function exportPng(canvas: Canvas, artboard: Bounds) {
  return canvas.toDataURL({ format: 'png', multiplier: 1, ...artboard });
}
Enter fullscreen mode Exit fullscreen mode

Zoom and pan that drift

If you zoom by changing the viewport transform around the origin, the content slides away from the cursor, and zooming in feels like you are chasing the picture. Zoom around the pointer instead. Clamp the zoom level as well, or a few notches of the wheel take you to a scale where nothing is usable.

import { Point, type Canvas } from 'fabric';

export function enableWheelZoom(canvas: Canvas) {
  canvas.on('mouse:wheel', (opt) => {
    opt.e.preventDefault();
    const next = canvas.getZoom() * 0.999 ** opt.e.deltaY;
    const zoom = Math.min(8, Math.max(0.1, next));
    canvas.zoomToPoint(opt.viewportPoint, zoom);
    canvas.requestRenderAll();
  });
}
Enter fullscreen mode Exit fullscreen mode

Space+drag and fit to screen use the same transform, so keep them in one place. Splitting the logic across handlers is how the pan and the zoom start to disagree.

Z-order and layers

Fabric keeps stacking order in the objects array. Reordering that array by hand is easy to get wrong, and when it goes wrong the layers panel shows a different order from the one on the canvas. Use the canvas methods instead, and bind them to keys, so the panel and the canvas always work from the same order.

import type { Canvas } from 'fabric';

export function bindLayerKeys(canvas: Canvas) {
  window.addEventListener('keydown', (e) => {
    const obj = canvas.getActiveObject();
    if (!obj) return;
    if (e.key === ']') canvas.bringObjectForward(obj);
    if (e.key === '[') canvas.sendObjectBackwards(obj);
    canvas.requestRenderAll();
  });
}
Enter fullscreen mode Exit fullscreen mode

The starter kit

Everything above except undo and redo is wired up in Kanvaskit Lite, a free MIT-licensed starter kit I built on React 19, TypeScript 6, Fabric.js 7, Zustand 5 and Zod 4. The code is at https://github.com/debojitsaha/kanvaskit-lite, and the live demo is at https://debojitsaha.github.io/kanvaskit-lite/.

If you want undo/redo, templates and PDF export, there's a Pro version coming; the waitlist is here: https://kanvaskit.netlify.app/?utm_source=devto&utm_medium=article&utm_campaign=lite-launch

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.