Fabric.js provides a texture brush (PatternBrush) functionality for drawing with image-based patterns. The following outlines the core implementation steps and configuration.
Core Implementation Steps
1. Enable Drawing Mode
Initialize a canvas with isDrawingMode set to true.
const canvas = new fabric.Canvas('canvasElementId', {
width: 400,
height: 400,
isDrawingMode: true
});
2. Load the Image Source
Create an Image object and set its source.
const patternImage = new Image();
patternImage.src = './texture-image.jpg';
3. Initialize the Pattern Brush
Instantiate a fabric.PatternBrush object, passing the canvas as an argument.
patternImage.onload = function() {
const textureBrush = new fabric.PatternBrush(canvas);
4. Configure the Brush Source and Properties
Assign the loaded image to the brush's source property. The brush width can be adjusted via the width property.
textureBrush.source = patternImage;
textureBrush.width = 50; // Set the stroke width
5. Activate the Brush on the Canvas
Set the canvas's free drawing brush to the configured PatternBrush instance.
canvas.freeDrawingBrush = textureBrush;
};
Important Consideration
All brush configuration must ocurr inside the image's onload event handler to ensure the source image is fully loaded before the brush is used.
Example Configuration Summary
const myCanvas = new fabric.Canvas('myCanvas', { isDrawingMode: true });
const img = new Image();
img.src = './pattern.png';
img.onload = () => {
const myPatternBrush = new fabric.PatternBrush(myCanvas);
myPatternBrush.source = img;
myPatternBrush.width = 30;
myCanvas.freeDrawingBrush = myPatternBrush;
};