Overview
Fabric.js provides drawing capabilities when the canvas is set to drawing mode. This guide covers the fundamental brush configuration options.
Note: This guide uses Fabric.js version 5.2.1
Initial Setup
Enable drawing mode on the canvas to activate brush funcsionality:
<canvas id="canvas" width="600" height="400" style="border: 1px solid #ccc;"></canvas>
<script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/521/fabric.js"></script>
<script>
const canvas = new fabric.Canvas('canvas', {
isDrawingMode: true
});
</script>
Set isDrawingMode to true during initialization, or toggle it later with canvas.isDrawingMode = true.
Brush Width
Control the thickness of the brush stroke:
canvas.freeDrawingBrush.width = 25;
Brush Color
Define the stroke color:
canvas.freeDrawingBrush.color = '#ff6b6b';
Dashed Stroke Pattern
Create dashed lines using strokeDashArray:
canvas.freeDrawingBrush.strokeDashArray = [15, 30];
The array accepts multiple values to define alternating dash and gap lengths.
Shadow Effect
Apply shadow to brush strokes:
canvas.freeDrawingBrush.shadow = new fabric.Shadow({
blur: 8,
offsetX: 5,
offsetY: 5,
color: 'rgba(0, 0, 0, 0.3)'
});
Constrain Drawing to Canvas
Prevent strokes from extending beyond canvas boundaries:
canvas.freeDrawingBrush.limitedToCanvasSize = true;
Line Cap Style
Define the appearance of line endings:
canvas.freeDrawingBrush.strokeLineCap = 'round';
Available options: round, butt, square. Default is round.
Line Join Style
Control how line segments connect:
canvas.freeDrawingBrush.strokeLineJoin = 'miter';
Options include: miter, bevel, round.
Miter Limit
Set the miter limit for line joins:
canvas.freeDrawingBrush.strokeLineJoin = 'miter';
canvas.freeDrawingBrush.strokeMiterLimit = 10;
This property only takes effect when strokeLineJoin is set to miter.
Common Use Cases
- Image annotation tools
- Document markup systems
- Simple drawing applications
- Signature capture
These configuration options provide the foundation for implementing custom drawing features in web applications.