How to add shadow to objects in canvas using FabricJS?

Mandev
3 min readNov 21, 2022

--

In this article I will demonstrate how you can use the shadow class to add a shadow to objects in FabricJS.

Here is the constructor definition:

new fabric.Shadow(options: Object): fabric.Shadow

As you can see from the constructor definition above, this class accepts an optional options Object where you can specify the blur, offsetX, offsetY, color and other properties that you want related to the Shadow.

Adding a shadow to a circle object in FabricJS

The first step is to create an instance of fabric.Shadow in order to create a Shadow object.

The second step is to assign that shadow object to the shadow property for the required object. The idea is that a rectangle object’s shadow will be rectangular, a circle object’s shadow will be circular and so on.

Here’s how you can do that:

  var canvas = new fabric.Canvas("canvas", {
backgroundColor: "black",
});

// Initiate a shadow object
var shadow = new fabric.Shadow({
color: "white",
blur: 7,
offsetX: 20,
offsetY: 20,
});

// Initiate a circle object
var circle = new fabric.Circle({
top: 80,
left: 50,
radius: 50,
fill: "#9bddff",
shadow: shadow,
});

canvas.add(circle);
You can see that the shadow for the circle object is also circular in nature

Adding Shadow to a Polyline object using FabricJS

You might be wondering how the shadow for a Line or Polyline object might look like. Well, to answer your question, the shadow of a stick is going to look like a stick 😶 it’s not going to look like a hamster, is it?

But to prove my point, that the shadow of the object is going to emulate its shape, let’s look at an example that demonstrates how we can add a shadow to a Polyline object.

      var canvas = new fabric.Canvas("canvas", {
backgroundColor: "black",
});

// Initiate a shadow object
var shadow = new fabric.Shadow({
color: "white",
blur: 7,
offsetX: 20,
offsetY: 20,
});

// Initiate a polyline object
var polylineObj = new fabric.Polyline(
[
{ x: 90, y: 60 },
{ x: 84, y: 155 },
{ x: 49, y: 154 },
{ x: 122, y: 80 },
],
{
top: 80,
left: 50,
fill: "#9bddff",
shadow: shadow,
}
);

canvas.add(polylineObj);
output

Like all other classes in FabricJS, the Shadow class also has its set of properties and methods that we can leverage according to our needs.

Here are a few of them:

  1. blur: This property accepts a Number. It is used to set the shadow blur.
  2. color: It accepts a String value determining the shadow color. It’s default value is rgb(0,0,0) ie., the color black.
  3. offsetX: It accepts a Number that determines the shadow offset in the x-direction.
  4. offsetY: It accepts a Number that determines the shadow offset in the y-direction.

In the next article we’ll see how we can animate objects on the canvas!

--

--