IText is an editable text element in Fabric.js. While fill sets color for all text, customizing specific characters requires the styles object. This guide covers global styling, single/multi-line character styling, and background colors.
Setup
<canvas id="canvas" width="600" height="400" style="border: 1px solid #ddd;"></canvas>
<script src="https://cdn.jsdelivr.net/npm/fabric@5.2.1/dist/fabric.min.js"></script>
<script>
const fabricCanvas = new fabric.Canvas('canvas');
const textElement = new fabric.IText('hello fabric');
fabricCanvas.add(textElement);
</script>
Include Fabric.js, initialize the canvas, and create an IText element.
Global Text Color (Fill)
To color all text, use fill:
const textElement = new fabric.IText('global color demo', {
fill: 'lightblue' // Applies to all characters
});
fill works differently from CSS’s color—it sets the text’s fill color in Fabric.js.
Single-Line: Specific Character Color
To style individual characters, use the styles object (indices start at 0 for lines/characters):
const textElement = new fabric.IText('hello', {
styles: {
0: { // First line (index 0)
2: { // Third character (index 2, "l")
fill: 'crimson'
}
}
}
});
This colors the third character (index 2) of the first line red. The styles object maps line indices to character indices, with style properties.
Multi-Line: Specific Character Color
For multi-line text (use \n for newlines), extend styles to multiple rows:
const textElement = new fabric.IText('hello\nfabric', {
styles: {
0: { // First line
1: { // Second character ("e")
fill: 'red'
}
},
1: { // Second line
3: { // Fourth character ("r")
fill: 'purple'
}
}
}
});
Newlines use \n, and each line is indexed separately (e.g., line 0, line 1).
Text Background Color
To set a character’s background color, use textBackgroundColor in styles:
const textElement = new fabric.IText('styled text', {
styles: {
0: {
3: { // Fourth character ("e")
textBackgroundColor: 'lime', // Background color
}
}
}
});
textBackgroundColor works like fill but applies to the text’s background.