soywod
soywod

Reputation: 4510

Add style to `clipPath` Fabric.js Object

I need a canvas with a specific shape. I was able to do so thanks to this post using clipPath. The problem is I can't style it at all.

Here an example with a circle shaped canvas. I try to apply the same style to the object inside the container and to the container itself, but as you can see only the object inside the container is styled. How can I apply a stroke or a shadow to this circle container (clipPath)?

const canvas = new fabric.Canvas("canvas", {backgroundColor: "#d3d3d3"})

const container = new fabric.Circle({
  radius: 150,
  left: 50,
  top: 50,
  stroke: "rgba(0, 0, 0, 0.5)",
  strokeWidth: 1,
})

const obj = new fabric.Rect({
  width: 100,
  height: 100,
  left: 150,
  top: 150,
  fill: "blue",
  stroke: "rgba(0, 0, 0, 0.5)",
  strokeWidth: 1,
})

const shadow = new fabric.Shadow({
  color: "rgba(0, 0, 0, 0.5)",
  blur: 10,
})

container.set("shadow", shadow)
obj.set("shadow", shadow)

canvas.clipPath = container
canvas.add(obj)

canvas.requestRenderAll()
#canvas {
  background: #e8e8e8;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.0.0-beta.5/fabric.min.js"></script>

<canvas id="canvas" width="400" height="400"></canvas>

[EDIT] I found a company who does that: https://www.plaqueomatic.fr/plaqueomatic/plastique. They use fabric v3.6.0. How can I achieve the same?

enter image description here

Upvotes: 2

Views: 2453

Answers (1)

melchiar
melchiar

Reputation: 2862

When clipping the canvas itself, styles like dropshadows are best applied using CSS. I've also enabled the controlsAboveOverlay property to make the resizing controls visible outside the clippath (feel free to disable if you don't need that).

const canvas = new fabric.Canvas("canvas", {
  backgroundColor: "#d3d3d3",
  controlsAboveOverlay: true
})

const container = new fabric.Circle({
  radius: 150,
  left: 50,
  top: 50,
  stroke: "rgba(0, 0, 0, 0.5)",
  strokeWidth: 1,
})

const obj = new fabric.Rect({
  width: 100,
  height: 100,
  left: 150,
  top: 150,
  fill: "blue",
  stroke: "rgba(0, 0, 0, 0.5)",
  strokeWidth: 1,
})

const shadow = new fabric.Shadow({
  color: "rgba(0, 0, 0, 0.5)",
  blur: 10,
})

obj.set("shadow", shadow)

canvas.clipPath = container
canvas.add(obj)

canvas.requestRenderAll()
#canvas {
  -webkit-filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.5));
  filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.5));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.0.0-beta.5/fabric.min.js"></script>

<canvas id="canvas" width="400" height="400"></canvas>

Upvotes: 3

Related Questions