Aligning Guidelines

This page demonstrates the alignment guidelines feature for different widgets using XRectNotes and XCircleNotes from @boardxus/canvasx-core. When moving or arranging objects, alignment guidelines appear to help you visually align and distribute widgets on the canvas. This is useful for diagramming, layout, and precise positioning.

How to use it

import { initAligningGuidelines } from "fabric/extensions";

const config = {
  // distance from the shape does alignment begin?
  margin: 4,
  // guideline dimensions
  width: 1,
  // guideline color
  color: "rgba(255,0,0,0.9)",
  // close vertical line, default false
  closeVLine: false,
  // close horizontal line, default false
  closeHLine: false,
};

const deactivate = initAligningGuidelines(myCanvas, config);

// To disable alignment guidelines later:
deactivate();

Custom function examples

// Compare only with sibling elements
initAligningGuidelines(myCanvas, {
  getObjectsByTarget: function (target) {
    const set = new Set<FabricObject>();
    const p = target.parent ?? target.canvas;
    p?.getObjects().forEach((o) => set.add(o));
    return set;
  },
});

// Align only the TL control point
initAligningGuidelines(myCanvas, {
  getPointMap: function (target) {
    const tl = target.getCoords().tl;
    return { tl };
  },
});

// Custom controllers and control points
FabricObject.createControls = function () {
  // controllers
  return { controls: { abc: new Control({}) } };
};
initAligningGuidelines(myCanvas, {
  getPointMap: function (target) {
    const abc = target.getCoords().tl;
    return { abc };
  },
  getContraryMap: function (target) {
    const abc = target.aCoords.br;
    return { abc };
  },
  contraryOriginMap: {
    // if the top-left point, then the reference point is the bottom-right.
    abc: ["right", "bottom"],
  },
});

// Close all guidelines
initAligningGuidelines(myCanvas, {
  closeVLine: true,
  closeHLine: true,
  getPointMap: function (_) {
    return {};
  },
});

Contributors