Skip to content

guesant/fabricjs-object-fit

Repository files navigation

fabricjs-object-fit

Check Deploy Docs Dependabot CodeQL GitHub stars GitHub license npm version pkg.pr.new

CSS-like object-fit and object-position behavior for Fabric.js (v7+).

What is this?

When you place an image on a Fabric.js canvas, there is no built-in way to say "fit this image inside a 400×400 box without distortion." In the browser, CSS object-fit solves this in one property. fabricjs-object-fit brings that same behavior to Fabric.js:

  • cover fills the container, cropping the overflow
  • contain fits inside the container, letterboxing the rest
  • fill stretches to match exactly
  • none displays at original size, clipping overflow
  • scale-down like contain, but never scales up

It also supports object-position (pixel, percentage, or named anchors) and round-trips through Fabric.js serialization (toJSON / loadFromJSON).

Quick Start

pnpm add fabricjs-object-fit fabric
import * as fabric from "fabric";
import { setup, Point } from "fabricjs-object-fit";

const { ObjectFit } = setup(fabric);

const canvas = new fabric.Canvas("c");

const img = await fabric.FabricImage.fromURL("https://placehold.co/640x360");

const container = new ObjectFit(img, {
  width: 400,
  height: 400,
  mode: "cover", // "cover" | "contain" | "fill" | "none" | "scale-down"
  position: {
    x: Point.X.CENTER,
    y: Point.Y.CENTER,
  },
});

canvas.add(container);
canvas.renderAll();

Documentation

Read the full guide and browse the API documentation.

License

About

CSS like "object-fit" and "object-position" behavior for FabricJS

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors