To build gradient effects in a Vue 3 application using Fabric.js, you can create both linear and radial color transitions directly on canvas objects. Thelux explained demonstrates how to define, configure, and apply these gradients.
Start by scaffolding a Vue 3 project with Vite if needed:
npm init @vitejs/app
Select Vue 3 and complete the prompts. Then add Fabric.js:
npm install fabric --save
With the environment ready, you can instantiate a Fabric canvas and draw shapes with gradient fills.
Creating a Linear Gradient
A linear gradient spans between two points defined by coordinate pairs. Here's an example that applies a multi-stop rainbow gradient to a circle.
<template>
<canvas width="600" height="600" id="linearCanvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function mountLinearDemo() {
const canvas = new fabric.Canvas('linearCanvas')
const shape = new fabric.Circle({
left: 80,
top: 80,
radius: 60,
})
const fillGradient = new fabric.Gradient({
type: 'linear',
gradientUnits: 'pixels',
coords: {
x1: 0,
y1: 0,
x2: shape.width,
y2: 0,
},
colorStops: [
{ offset: 0, color: '#e66465' },
{ offset: 0.2, color: '#f6b73c' },
{ offset: 0.5, color: '#4d9f0c' },
{ offset: 0.8, color: '#1e90ff' },
{ offset: 1, color: '#8a2be2' },
],
})
shape.set('fill', fillGradient)
canvas.add(shape)
}
onMounted(() => {
mountLinearDemo()
})
</script>
The coords object defines the gradient extension over the shape. The colorStops array interleaves i positions (0 to 1) with CSS color values.
Defining a Radial Gradient
Radial gradients require additional properties to control inner and outer circles. The r1 and r2 values set the radii, while x1, y1 mark the focal point and x2, y2 locate the center.
<template>
<canvas width="600" height="600" id="radialCanvas" style="border: 1px solid #ccc;"></canvas>
</template>
<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
function mountRadialDemo() {
const canvas = new fabric.Canvas('radialCanvas')
const ball = new fabric.Circle({
left: 120,
top: 90,
radius: 55,
})
const radialFill = new fabric.Gradient({
type: 'radial',
gradientUnits: 'pixels',
coords: {
r1: ball.radius,
r2: 0,
x1: ball.radius,
y1: ball.radius,
x2: ball.radius,
y2: ball.radius,
},
colorStops: [
{ offset: 0, color: '#f9f586' },
{ offset: 0.7, color: '#f7971e' },
{ offset: 1, color: '#d91857' },
],
})
ball.set('fill', radialFill)
canvas.add(ball)
}
onMounted(() => {
mountRadialDemo()
})
</script>
Adjusting r1, r2, and the coordinate pairs alters the spread and focus of the gradient. Experimenting with these values helps55internalize how radial fills behave on the canvas. Both gradient types support either pixels or percentage units via the gradientUnits option, providing flexibility for responsivealeb designaths.