### 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