Skip to content

Working with gradients

kangax edited this page Nov 18, 2011 · 7 revisions

Fabric provides convenient support for color gradients.

Gradient-based fill can be given to any fabric object via setGradientFill method. To remove gradient, simply assign something else to object's "fill" property.

Here's a simple example of creating a circle with black-to-white gradient, spanning fully from object's top to bottom:

var canvas = new fabric.Canvas(...);
...
var circle = new fabric.Circle({
  left: 100,
  top: 100,
  radius: 50
});

circle.setGradientFill(canvas.getContext(), {
  x1: 0,
  y1: 0,
  x2: 0,
  y2: circle.height,
  colorStops: {
    0: '#000',
    1: '#fff'
  }
});

Notice how the gradient is defined by its top boundary (x1, y1), bottom boundary (x2, y2), and a set of color stops (colorStops).