Skip to content

Working with gradients

mindjuice edited this page Nov 24, 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) where each color stop is a key (in 0 to 1 range) and a value (any supported color).

Here's an example of left-to-right, red-blue gradient:

circle.setGradientFill(canvas.getContext(), { 
  x1: 0,
  y1: circle.height / 2,
  x2: circle.width,
  y2: circle.height / 2,
  colorStops: {
    0: "red",
    1: "blue"
  }
});

And this is 5-stops rainbow gradient:

circle.setGradientFill(canvas.getContext(), { 
  x1: 0,
  y1: circle.height / 2,
  x2: circle.width,
  y2: circle.height / 2,
  colorStops: {
    0: "red",
    0.2: "orange",
    0.4: "yellow",
    0.6: "green",
    0.8: "blue",
    1: "purple"
  }
});

In addition, you can set the boundaries of the gradient (x1,y1, x2,y2) using percentages instead of pixel values.

var redToOrangeGradient = {
  x1: "0%",   // For a vertical gradient, the x1 & y1 don't matter as long as they are the same
  y1: "0%",   // The top of the gradient will be at the top of the object
  x2: "0%",
  y2: "100%", // The bottom of the gradient will be at the bottom of the object
  colorStops: {
    0: "#FF0000",
    1: "#FFFF00"
  }
};

Note that once the gradient has been created though, the percentages are changed internally to integer pixel values, so this gradient objectcannot be reused for another object of a different size.