Implementing and Customizing the Circle Brush in Fabric.js

To utilize Fabric.js for free-hand drawing with a unique dotted effect, you must first activate the drawing mode on the canvas. This is achieved by setting the isDrawingMode property to true. The following code initializes the canvas and enables this mode.

const canvas = new fabric.Canvas('myCanvas', {
    width: 800,
    height: 500,
    isDrawingMode: true // Activate drawing mode
});

To replace the default brush with the circle brush, you assign an instance of fabric.CircleBrush to the freeDrawingBrush property.

let circleBrush = new fabric.CircleBrush(canvas);
canvas.freeDrawingBrush = circleBrush;

A alternative initialization method provides more direct control over the brush object.

let myCircleBrush = new fabric.CircleBrush();
myCircleBrush.initialize(canvas); // Link brush to the canvas
canvas.freeDrawingBrush = myCircleBrush;

You can modify the visual properties of the brush to customize the drawing output.

// Adjust the diameter of the drawn circles
myCircleBrush.width = 8;

// Change the fill color of the circles
myCircleBrush.color = '#3498db';
// Other color formats are also supported
// myCircleBrush.color = 'rgba(231, 76, 60, 0.7)';

// Add a shadow effect to each circle
myCircleBrush.shadow = new fabric.Shadow({
    color: '#2c3e50',
    blur: 5,         // Shadow blur radius
    offsetX: 3,      // Horizontal offset
    offsetY: 3       // Vertical offset
});

The circle brush exposes several event handlers that allow you to inject custom logic during the drawing process.

// Triggered when the mouse button is pressed
myCircleBrush.onMouseDown = function(point, event) {
    console.log('Brush active at:', point);
    // Custom pre-draw logic can go here
};

// Triggered when the mouse button is released
myCircleBrush.onMouseUp = function() {
    console.log('Brush stroke ended');
    // Custom post-draw logic can go here
};

// Triggered as the mouse moves while drawing
myCircleBrush.onMouseMove = function(point, event) {
    // Essential: Call the internal method to render the circle
    this.drawDot(point);
    // Optional: Add additional points to the path for more complex effects
    // this.addPoint({ x: point.x + 20, y: point.y - 10 });
};

It is important to call this.drawDot(point) inside the onMouseMove handler to ensure the circles are rendered at the cursor's position. Without this call, the visual feedback for the brush stroke will not appear.

Tags: fabric.js javascript Canvas Drawing Brush

Posted on Tue, 04 Aug 2026 16:54:35 +0000 by dbrimlow