### Complete Text Rendering Example Source: https://github.com/fabricjs/fabric.js/wiki/How-to-render-text-with-Cufon-(deprecated) A full HTML example demonstrating text rendering with a custom font and styling. ```APIDOC ## Complete Text Rendering Example ### Description This comprehensive example includes the necessary HTML structure, script includes for Fabric.js and a custom font, and JavaScript code to render styled text on a canvas. ### Method N/A (Client-side JavaScript) ### Endpoint N/A (Client-side JavaScript) ### Parameters None ### Request Example ```html Text Rendering Example ``` ### Response #### Success Response (200) N/A (Client-side operation) #### Response Example N/A ``` -------------------------------- ### Project Setup and Build Commands Source: https://github.com/fabricjs/fabric.js/blob/master/CLAUDE.md Commands to initialize the development environment and execute build processes. These commands are essential for preparing the workspace and compiling the project. ```bash npm i --include=dev npm run build npm run build:fast ``` -------------------------------- ### Applying Gradient Fill to a Circle Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-gradients This example demonstrates how to create a circle and apply a black-to-white gradient fill that spans from top to bottom. ```APIDOC ## Applying Gradient Fill to a Circle ### Description This example demonstrates how to create a circle and apply a black-to-white gradient fill that spans from top to bottom. ### Method `setGradientFill` ### Endpoint N/A (Client-side JavaScript) ### Parameters #### Request Body (for `setGradientFill`) - **x1** (number) - The x-coordinate of the starting point of the gradient. - **y1** (number) - The y-coordinate of the starting point of the gradient. - **x2** (number) - The x-coordinate of the ending point of the gradient. - **y2** (number) - The y-coordinate of the ending point of the gradient. - **colorStops** (object) - An object where keys are color stop positions (0 to 1) and values are CSS color strings. ### Request Example ```javascript var canvas = new fabric.Canvas('c'); var circle = new fabric.Circle({ left: 100, top: 100, radius: 50 }); circle.setGradientFill({ x1: 0, y1: 0, x2: 0, y2: circle.height, colorStops: { 0: '#000', 1: '#fff' } }); canvas.add(circle); ``` ### Response #### Success Response (200) N/A (Modifies object in place) #### Response Example N/A ``` -------------------------------- ### Pull latest changes Source: https://github.com/fabricjs/fabric.js/wiki/Releasing-new-version Synchronize the local repository with the remote before starting the release process. ```bash git pull --rebase ``` -------------------------------- ### Install Fabric.js via package managers Source: https://github.com/fabricjs/fabric.js/blob/master/README.md Use these commands to add the fabric package to your project dependencies. ```bash $ npm install fabric --save # or use yarn $ yarn add fabric # or use pnpm $ pnpm install fabric ``` -------------------------------- ### Install Fabric.js Origin Updater Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/data_updaters/origins/README.md This snippet shows how to import and install the Origin Updater extension in your Fabric.js project. This wrapper modifies the `fromObject` function to set default `originX` and `originY` values while preserving the visual position of fabric instances. ```typescript import { installOriginWrapperUpdater } from 'fabric/extensions'; installOriginWrapperUpdater(); ``` -------------------------------- ### Initialize Fabric.js Canvas in Plain HTML Source: https://github.com/fabricjs/fabric.js/blob/master/README.md Basic setup for using Fabric.js in a plain HTML file. Includes canvas element and script tags for initialization and adding a rectangle. ```html ``` -------------------------------- ### Install Fabric.js Origin Updater with Custom Defaults Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/data_updaters/origins/README.md This snippet demonstrates how to install the Origin Updater extension with custom default values for `originX` and `originY`. This is useful when your application uses specific default origins that differ from Fabric.js's built-in defaults. ```typescript import { installOriginWrapperUpdater } from 'fabric/extensions'; installOriginWrapperUpdater(0.2, 'bottom'); ``` -------------------------------- ### Complete Text Rendering Example (HTML/JavaScript) Source: https://github.com/fabricjs/fabric.js/wiki/How-to-render-text-with-Cufon-(deprecated) A full HTML page demonstrating text rendering with Fabric.js. It includes loading the Fabric.js library, a custom font file, and JavaScript code to create and add a styled text object to the canvas. ```html Text Rendering Example ``` -------------------------------- ### Customizing Guideline Endpoints in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Explains how to customize the appearance of guideline endpoints by overriding the `drawX` function. This example draws a solid circle for the start point and a hollow circle for the end point. ```typescript import { AligningGuidelines } from 'fabric/extensions'; // If you don't like the endpoints being "X," you can customize the endpoints. For example, the start point can be a solid circle, and the end point can be a hollow circle. new AligningGuidelines(myCanvas, { drawX(point: Point, dir: number) { const ctx = this.canvas.getTopContext(); const zoom = this.canvas.getZoom(); const size = this.xSize / zoom; ctx.save(); ctx.translate(point.x, point.y); ctx.beginPath(); ctx.arc(0, 0, size, 0, Math.PI * 2); if (dir == -1) { ctx.fillStyle = this.color; ctx.fill(); } else { ctx.stroke(); } ctx.restore(); }, }); ``` -------------------------------- ### Left-to-Right Red-Blue Gradient Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-gradients This example shows how to apply a red-to-blue gradient that spans horizontally across the object. ```APIDOC ## Left-to-Right Red-Blue Gradient ### Description This example shows how to apply a red-to-blue gradient that spans horizontally across the object. ### Method `setGradientFill` ### Endpoint N/A (Client-side JavaScript) ### Parameters #### Request Body (for `setGradientFill`) - **x1** (number) - The x-coordinate of the starting point of the gradient. - **y1** (number) - The y-coordinate of the starting point of the gradient. - **x2** (number) - The x-coordinate of the ending point of the gradient. - **y2** (number) - The y-coordinate of the ending point of the gradient. - **colorStops** (object) - An object where keys are color stop positions (0 to 1) and values are CSS color strings. ### Request Example ```javascript circle.setGradientFill({ x1: 0, y1: circle.height / 2, x2: circle.width, y2: circle.height / 2, colorStops: { 0: "red", 1: "blue" } }); ``` ### Response #### Success Response (200) N/A (Modifies object in place) #### Response Example N/A ``` -------------------------------- ### Fabric.js Server-Side Rendering with Node.js Source: https://github.com/fabricjs/fabric.js/blob/master/README.md Example of using Fabric.js in a Node.js environment to create an HTTP server that serves images generated by Fabric.js. Supports viewing, downloading, or displaying the image directly. ```javascript import http from 'http'; import * as fabric from 'fabric/node'; // v6 import { fabric } from 'fabric'; // v5 const port = 8080; http .createServer((req, res) => { const canvas = new fabric.Canvas(null, { width: 100, height: 100 }); const rect = new fabric.Rect({ width: 20, height: 50, fill: '#ff0000' }); const text = new fabric.Text('fabric.js', { fill: 'blue', fontSize: 24 }); canvas.add(rect, text); canvas.renderAll(); if (req.url === '/download') { res.setHeader('Content-Type', 'image/png'); res.setHeader('Content-Disposition', 'attachment; filename="fabric.png"'); canvas.createPNGStream().pipe(res); } else if (req.url === '/view') { canvas.createPNGStream().pipe(res); } else { const imageData = canvas.toDataURL(); res.writeHead(200, '', { 'Content-Type': 'text/html' }); res.write(``); res.end(); } }) .listen(port, (err) => { if (err) throw err; console.log( `> Ready on http://localhost:${port}, http://localhost:${port}/view, http://localhost:${port}/download`, ); }); ``` -------------------------------- ### Customizing Alignment Points for Guidelines in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Illustrates how to customize the alignment points using the `getPointMap` function. This example specifically aligns based on the top-left (TL) control point of a target object. ```typescript import { AligningGuidelines } from 'fabric/extensions'; // You can customize the alignment point, the example only aligns the TL control point new AligningGuidelines(myCanvas, { getPointMap: function (target) { const tl = target.getCoords().tl; return { tl }; }, }); ``` -------------------------------- ### Customizing Guideline Drawing with Bézier Curves in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Demonstrates how to override the default line drawing behavior by providing a custom `drawLine` function. This example uses `bezierCurveTo` to draw curved alignment lines instead of straight ones. ```typescript import { AligningGuidelines } from 'fabric/extensions'; // You can customize drawing line segments. What if you want to draw a Bézier curve? new AligningGuidelines(myCanvas, { drawLine(origin, target) { const ctx = this.canvas.getTopContext(); const viewportTransform = this.canvas.viewportTransform; const zoom = this.canvas.getZoom(); ctx.save(); ctx.transform(...viewportTransform); ctx.lineWidth = this.width / zoom; if (this.lineDash) ctx.setLineDash(this.lineDash); ctx.strokeStyle = this.color; ctx.beginPath(); ctx.moveTo(origin.x, origin.y); const controlPoint1 = { x: (origin.x + target.x) / 3, y: origin.y - 50 }; // 控制点1 const controlPoint2 = { x: (origin.x + target.x) / 3, y: target.y + 50 }; // 控制点2 ctx.bezierCurveTo( controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, target.x, target.y, ); ctx.stroke(); if (this.lineDash) ctx.setLineDash([]); this.drawX(origin, -1); this.drawX(target, 1); ctx.restore(); }, }); ``` -------------------------------- ### Disabling Vertical and Horizontal Guidelines in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Provides an example of how to disable both vertical and horizontal alignment lines by setting `closeVLine` and `closeHLine` to `true`. It also includes an empty `getPointMap` to ensure no specific points are targeted for alignment. ```typescript import { AligningGuidelines } from 'fabric/extensions'; // You can close all new AligningGuidelines(myCanvas, { closeVLine: true, closeHLine: true, getPointMap: function (_) { return {}; }, }); ``` -------------------------------- ### Initialize and Dispose Aligning Guidelines in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Demonstrates how to initialize AligningGuidelines with custom configuration options like margin, width, color, and how to dispose of them to disable alignment. ```typescript import { AligningGuidelines } from 'fabric/extensions'; const config = { /** At what distance from the shape does alignment begin? */ margin: 4, /** Aligning line dimensions */ width: 1, /** Aligning line color */ color: 'rgba(255,0,0,0.9)', /** Close Vertical line, default false. */ closeVLine: false, /** Close horizontal line, default false. */ closeHLine: false, }; const aligningGuidelines = new AligningGuidelines(myCanvas, config); // in order to disable alignment guidelines later: aligningGuidelines.dispose(); ``` -------------------------------- ### Tag new version Source: https://github.com/fabricjs/fabric.js/wiki/Releasing-new-version Create a version tag and push it to the remote repository. ```bash git tag v1.x.x git push --tags ``` -------------------------------- ### Publish to npm Source: https://github.com/fabricjs/fabric.js/wiki/Releasing-new-version Publish the package to the npm registry. ```bash npm publish ``` -------------------------------- ### Define Gradients Using Percentage Coordinates Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-gradients Shows how to define gradient boundaries using percentage strings instead of pixel values. This allows for responsive gradient positioning relative to the object's bounding box. ```javascript var redToOrangeGradient = { x1: "50%", y1: "0%", x2: "50%", y2: "100%", colorStops: { 0: "#FF0000", 1: "#FFFF00" } }; ``` -------------------------------- ### Configuring Dashed Lines and Endpoint Size for Guidelines in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Shows how to configure dashed alignment lines using the `lineDash` property and adjust the size of the endpoints with `xSize`. This allows for visual customization of the guideline appearance. ```typescript import { AligningGuidelines } from 'fabric/extensions'; // You can set dashed lines. // You can adjust the size of endpoint x. new AligningGuidelines(myCanvas, { lineDash: [2, 2], xSize: 10, }); ``` -------------------------------- ### Gradient with Percentage Boundaries Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-gradients Illustrates using percentage values for gradient boundaries, noting that these are converted to pixel values. ```APIDOC ## Gradient with Percentage Boundaries ### Description Illustrates using percentage values for gradient boundaries, noting that these are converted to pixel values. ### Method `setGradientFill` ### Endpoint N/A (Client-side JavaScript) ### Parameters #### Request Body (for `setGradientFill`) - **x1** (string or number) - The x-coordinate of the starting point of the gradient (can be percentage string). - **y1** (string or number) - The y-coordinate of the starting point of the gradient (can be percentage string). - **x2** (string or number) - The x-coordinate of the ending point of the gradient (can be percentage string). - **y2** (string or number) - The y-coordinate of the ending point of the gradient (can be percentage string). - **colorStops** (object) - An object where keys are color stop positions (0 to 1) and values are CSS color strings. ### Request Example ```javascript var redToOrangeGradient = { x1: "50%", y1: "0%", x2: "50%", y2: "100%", colorStops: { 0: "#FF0000", 1: "#FFFF00" } }; // Note: Once applied, percentages are converted to pixel values and cannot be reused on different sized objects. // circle.setGradientFill(redToOrangeGradient); ``` ### Response #### Success Response (200) N/A (Modifies object in place) #### Response Example N/A ``` -------------------------------- ### Code Quality and Testing Commands Source: https://github.com/fabricjs/fabric.js/blob/master/CLAUDE.md Standard commands for maintaining code quality through linting and formatting, as well as executing unit and end-to-end tests. These ensure project stability and compliance with coding standards. ```bash npm run typecheck npm run lint npm run prettier:check npm run prettier:write npm run test:vitest npm run test:e2e ``` -------------------------------- ### Adding an Object to Fabric Canvas Source: https://github.com/fabricjs/fabric.js/wiki/How-to-set-additional-properties-in-all-fabric.Objects Demonstrates the standard way to instantiate a fabric.Text object and add it to the canvas. ```javascript const text = new fabric.Text(an.text, { left: 100, top: 100, }); canvas.add(text); ``` -------------------------------- ### Multi-stop Rainbow Gradient Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-gradients Demonstrates creating a gradient with multiple color stops for a rainbow effect. ```APIDOC ## Multi-stop Rainbow Gradient ### Description Demonstrates creating a gradient with multiple color stops for a rainbow effect. ### Method `setGradientFill` ### Endpoint N/A (Client-side JavaScript) ### Parameters #### Request Body (for `setGradientFill`) - **x1** (number) - The x-coordinate of the starting point of the gradient. - **y1** (number) - The y-coordinate of the starting point of the gradient. - **x2** (number) - The x-coordinate of the ending point of the gradient. - **y2** (number) - The y-coordinate of the ending point of the gradient. - **colorStops** (object) - An object where keys are color stop positions (0 to 1) and values are CSS color strings. ### Request Example ```javascript circle.setGradientFill({ x1: 0, y1: circle.height / 2, x2: circle.width, y2: circle.height / 2, colorStops: { 0: "red", 0.2: "orange", 0.4: "yellow", 0.6: "green", 0.8: "blue", 1: "purple" } }); ``` ### Response #### Success Response (200) N/A (Modifies object in place) #### Response Example N/A ``` -------------------------------- ### Registering Canvas Event Listeners Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-events Demonstrates how to attach event handlers to a Fabric.js canvas instance. It shows both individual event registration and batch registration using key-value pairs. ```javascript var canvas = new fabric.Canvas('my-canvas'); var moveHandler = function (evt) { var movingObject = evt.target; console.log(movingObject.get('left'), movingObject.get('top')); }; var modifiedHandler = function (evt) { var modifiedObject = evt.target; console.log(modifiedObject.get('left'), modifiedObject.get('top')); }; var customEvtHandler = function (evt) { console.log("I was triggered by a custom event."); }; canvas.on('object:moving', moveHandler); canvas.on('object:modified', modifiedHandler); canvas.on('custom:event', customEvtHandler); canvas.on({ 'object:moving' : moveHandler, 'object:modified' : modifiedHandler, 'custom:event' : customEvtHandler }); canvas.trigger("custom:event", {}); ``` -------------------------------- ### Initialize Fabric.js Canvas Markup Source: https://github.com/fabricjs/fabric.js/wiki/How-fabric-canvas-layering-works Demonstrates the transformation of a basic HTML canvas element into the Fabric.js managed container structure. This structure is required for interactive features like object selection and control rendering. ```html
``` -------------------------------- ### Update Object Shadow Configuration Source: https://github.com/fabricjs/fabric.js/wiki/Changelog-(draft) Replaces the deprecated setShadow method with the new set('shadow', ...) pattern to align with the updated object property management. ```javascript // Old pattern (deprecated) rect.setShadow(options); // New pattern rect.set('shadow', new fabric.Shadow(options)); ``` -------------------------------- ### Initialize Fabric.js Canvas in React.js Source: https://github.com/fabricjs/fabric.js/blob/master/README.md Integrate Fabric.js into a React component using `useEffect` and `useRef`. Ensures proper cleanup by disposing of the canvas instance on unmount. ```tsx import React, { useEffect, useRef } from 'react'; import * as fabric from 'fabric'; // v6 import { fabric } from 'fabric'; // v5 export const FabricJSCanvas = () => { const canvasEl = useRef(null); useEffect(() => { const options = { ... }; const canvas = new fabric.Canvas(canvasEl.current, options); // make the fabric.Canvas instance available to your app updateCanvasContext(canvas); return () => { updateCanvasContext(null); canvas.dispose(); } }, []); return ; }; ``` -------------------------------- ### Customizing Control Points and Alignment Maps in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Demonstrates advanced customization of control points and alignment behavior. It shows how to deactivate default controls, define custom controls, and map them for alignment using `getPointMap` and `getContraryMap`. ```typescript import { AligningGuidelines } from 'fabric/extensions'; import { InteractiveFabricObject } from 'fabric'; // deactivate constructor control assignment InteractiveFabricObject.createControls = function () { return {}; }; // custom controllers InteractiveFabricObject.ownDefaults.controls = { abc: new Control({}), }; // You can set control points for custom controllers new AligningGuidelines(myCanvas, { getPointMap: function (target) { const abc = target.getCoords().tl; return { abc }; }, getContraryMap: function (target) { const abc = target.aCoords.br; return { abc }; }, contraryOriginMap: { // If abc is the top-left point, then the reference point is the bottom-right. abc: ['right', 'bottom'], }, }); ``` -------------------------------- ### Configure E2E Test Runner Styles Source: https://github.com/fabricjs/fabric.js/blob/master/e2e/site/index.html Sets the global body background to black and ensures the Fabric.js wrapper element has a white background for visibility during tests. ```css body { padding: 0; margin: 0; background-color: black; } [data-fabric='wrapper'] { background-color: white; } ``` -------------------------------- ### Import Fabric.js for v6 and v5 Source: https://github.com/fabricjs/fabric.js/blob/master/README.md Import Fabric.js modules for browser and Node.js environments. Use 'fabric/node' for Node.js specific imports in v6. ```javascript // v6 import { Canvas, Rect } from 'fabric'; // browser import { StaticCanvas, Rect } from 'fabric/node'; // node // v5 import { fabric } from 'fabric'; ``` -------------------------------- ### Adding Text to Canvas Source: https://github.com/fabricjs/fabric.js/wiki/How-to-render-text-with-Cufon-(deprecated) Demonstrates how to create and add a basic text object to the Fabric.js canvas. ```APIDOC ## Adding Text to Canvas ### Description This example shows how to instantiate a `fabric.Text` object and add it to the canvas. Ensure the font file is loaded before creating the text object. ### Method `canvas.add()` ### Endpoint N/A (Client-side JavaScript) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript canvas.add(new fabric.Text('foo', { fontFamily: 'Delicious_500', left: 100, top: 100 })); ``` ### Response #### Success Response (200) N/A (Client-side operation) #### Response Example N/A ``` -------------------------------- ### Canvas Rendering Lifecycle Hook Source: https://github.com/fabricjs/fabric.js/wiki/How-fabric-canvas-layering-works Shows how to register a callback function that executes after the canvas has finished rendering its contents. This is useful for drawing custom overlays or performing post-render logic. ```javascript canvas.on('after:render', function() { // Custom logic after rendering }); ``` -------------------------------- ### Update Object Fill and Pattern Configuration Source: https://github.com/fabricjs/fabric.js/wiki/Changelog-(draft) Updates the way gradients and patterns are applied to objects, moving away from specific setter methods to the generic set('fill', ...) method. ```javascript // Old pattern (deprecated) rect.setGradient(options); rect.setPatternFill(options); rect.setColor(color); // New pattern rect.set('fill', new fabric.Gradient(otherOptions)); rect.set('fill', new fabric.Pattern(options)); rect.set('fill', color); ``` -------------------------------- ### Migrate Event Listeners Source: https://github.com/fabricjs/fabric.js/wiki/Changelog-(draft) Updates event handling to use the standardized on/off/fire methods, replacing the deprecated observe/stopObserving/trigger methods. ```javascript // Old pattern (deprecated) object.observe('event', callback); object.stopObserving('event', callback); object.trigger('event'); // New pattern object.on('event', callback); object.off('event', callback); object.fire('event'); ``` -------------------------------- ### Adding Custom Properties to Fabric Objects Source: https://github.com/fabricjs/fabric.js/wiki/How-to-set-additional-properties-in-all-fabric.Objects Shows how to attach a custom property like 'id' to a Fabric object instance. ```javascript const text = new fabric.Text(an.text, { left: 100, top: 100, }); text.id = 'text-1234' canvas.add(text); ``` -------------------------------- ### Apply Linear Gradients to Fabric.js Objects Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-gradients Demonstrates how to apply various linear gradients to a Fabric.js circle, including vertical, horizontal, and multi-stop rainbow patterns. The gradient is defined by coordinate boundaries and a colorStops object mapping positions to colors. ```javascript var canvas = new fabric.Canvas(...); var circle = new fabric.Circle({ left: 100, top: 100, radius: 50 }); // Black to white vertical gradient circle.setGradientFill({ x1: 0, y1: 0, x2: 0, y2: circle.height, colorStops: { 0: '#000', 1: '#fff' } }); // Red to blue horizontal gradient circle.setGradientFill({ x1: 0, y1: circle.height / 2, x2: circle.width, y2: circle.height / 2, colorStops: { 0: "red", 1: "blue" } }); // 5-stop rainbow gradient circle.setGradientFill({ x1: 0, y1: circle.height / 2, x2: circle.width, y2: circle.height / 2, colorStops: { 0: "red", 0.2: "orange", 0.4: "yellow", 0.6: "green", 0.8: "blue", 1: "purple" } }); ``` -------------------------------- ### Configure Global Selection Source: https://github.com/fabricjs/fabric.js/wiki/FAQ Enables or disables the ability for users to select objects on the canvas globally. ```javascript canvas.selection = false; ``` -------------------------------- ### Customizing MouseUp Event Handling Source: https://github.com/fabricjs/fabric.js/wiki/Working-with-events Wraps the internal _onMouseUp method to fire a custom 'object:mouseup' event when an object is active. It also manages event listener cleanup for mouse and touch interactions. ```javascript main.canvas._onMouseUp = (function(originalFn) { return function(e) { _this = main.canvas; _this.__onMouseUp(e); if (_this.getActiveObject()) { _this.fire('object:mouseup', { target: _this.getActiveObject() }, e); } removeListener(fabric.document, 'mouseup', _this._onMouseUp); fabric.isTouchSupported && removeListener(fabric.document, 'touchend', _this._onMouseUp); removeListener(fabric.document, 'mousemove', _this._onMouseMove); fabric.isTouchSupported && removeListener(fabric.document, 'touchmove', _this._onMouseMove); addListener(_this.upperCanvasEl, 'mousemove', _this._onMouseMove); fabric.isTouchSupported && addListener(_this.upperCanvasEl, 'touchmove', _this._onMouseMove); }; })(main.canvas.setActiveObject); ``` -------------------------------- ### Customizing Object Selection for Aligning Guidelines in Fabric.js Source: https://github.com/fabricjs/fabric.js/blob/master/extensions/aligning_guidelines/README.MD Shows how to customize the `getObjectsByTarget` function to define which sibling elements an object should align with. This allows for more granular control over alignment behavior. ```typescript import { AligningGuidelines } from 'fabric/extensions'; import { FabricObject } from 'fabric'; // You can customize the return graphic, and the example will only compare it with sibling elements new AligningGuidelines(myCanvas, { getObjectsByTarget: function (target) { const set = new Set(); const p = target.parent ?? target.canvas; p?.getObjects().forEach((o) => { set.add(o); }); // Please remember to exclude yourself, or you will always align with yourself. set.delete(target); return set; }, }); ``` -------------------------------- ### Manage Object Stacking Order Source: https://github.com/fabricjs/fabric.js/wiki/FAQ Methods to manipulate the z-order of objects on the canvas. Includes functions to move objects to the front, back, or a specific index, and a property to preserve stacking order during selection. ```javascript canvas.preserveObjectStacking = true; obj.bringToFront(); obj.bringForward(); obj.sendToBack(); obj.sendBackwards(); obj.moveTo(n); ``` -------------------------------- ### Implementing Dynamic Time Text Updates Source: https://github.com/fabricjs/fabric.js/wiki/Storing-animations Iterates through canvas objects to find text elements with the 'time' animation property and updates them with the current system time. ```javascript canvas.forEachObject(function(obj){ if (obj.get('type') == 'text') { if (obj.get('anim') == 'time') { obj.set('text', currentTime()); } } }); function currentTime () { var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); if (minutes < 10) {minutes = "0" + minutes;} var suffix = "AM"; if (hours >= 12) { suffix = "PM"; hours = hours - 12; } if (hours == 0) {hours = 12;} return hours+":"+minutes+" "+suffix; } ``` -------------------------------- ### Register Custom Font (JavaScript) Source: https://github.com/fabricjs/fabric.js/wiki/How-to-render-text-with-Cufon-(deprecated) Shows the structure of a font definition file used by Cufon for Fabric.js text rendering. This file registers font properties like `font-family` and glyph metrics. ```javascript Cufon.registerFont({ "w": 162, "face": { "font-family": "Delicious_500", "font-weight": 500, ... }); ``` -------------------------------- ### Add Text Object to Canvas (JavaScript) Source: https://github.com/fabricjs/fabric.js/wiki/How-to-render-text-with-Cufon-(deprecated) Demonstrates how to create and add a basic text object to a Fabric.js canvas. It highlights the use of `fontFamily` to specify a custom font, which must be pre-loaded. ```javascript canvas.add(new fabric.Text('foo', { fontFamily: 'Delicious_500', left: 100, top: 100 })); ``` -------------------------------- ### Configure Canvas Background Source: https://github.com/fabricjs/fabric.js/wiki/FAQ Setting the background color of the canvas area using standard CSS color strings or RGBA values. ```javascript canvas.backgroundColor = 'red'; canvas.backgroundColor = 'rgba(0, 255, 0, 0.5)'; ``` -------------------------------- ### Creating Custom Blink Animation for Fabric Objects Source: https://github.com/fabricjs/fabric.js/wiki/Storing-animations A recursive timeout function that toggles the fill color of a Fabric object to create a blinking effect on the canvas. ```javascript function startAnimate(obj) { setTimeout(function animate(obj) { if (obj.getFill() == '#000') { obj.set('fill', '#FFF'); } else { obj.set('fill', '#000'); } canvas.renderAll(); setTimeout(animate(obj), 1000); }, 1000); } ``` -------------------------------- ### Modify Object Properties Source: https://github.com/fabricjs/fabric.js/wiki/FAQ How to update object attributes using the set method. Note that setCoords must be called after changing properties that affect bounding boxes to ensure controls remain accurate. ```javascript obj.set('width', 100); obj.set({ width: 100, height: 50, fill: 'red' }); obj.setCoords(); ``` -------------------------------- ### Retrieve Canvas Objects Source: https://github.com/fabricjs/fabric.js/wiki/FAQ Methods to access objects currently on the canvas. Use getObjects to retrieve an array of all items or item(n) to access a specific object by its z-order index. ```javascript canvas.getObjects(); canvas.item(0); canvas.item(1); ``` -------------------------------- ### Monkey Patching Fabric.js for Custom Animation Properties Source: https://github.com/fabricjs/fabric.js/wiki/Storing-animations Extends the Fabric.js toObject method to include an 'anim' property. This allows custom data to be serialized and accessed during canvas iteration for dynamic updates. ```javascript fabric.Object.prototype.toObject = (function (toObject) { return function (additionalProperties) { const obj = additionalProperties.reduce((acc, key) => { acc[key] = this[key]; return acc; }, {}); return fabric.util.object.extend(toObject.call(this), { ...obj, anim: this.anim }); }; })(fabric.Object.prototype.toObject); ``` -------------------------------- ### Increase Object Clickable Area Source: https://github.com/fabricjs/fabric.js/wiki/FAQ Adjusts the padding property of an object to enlarge its bounding box, making it easier to select or click. ```javascript circle.set('padding', 10); ``` -------------------------------- ### Remove Objects from Canvas Source: https://github.com/fabricjs/fabric.js/wiki/FAQ Methods to clear the entire canvas or remove a specific object instance. ```javascript canvas.clear(); canvas.remove(myRect); ```