Skip to content Skip to sidebar Skip to footer

Setting Opacity To Canvas Fabricjs

After I draw polygon i would like to change opacity of canvas out of polygon i just drawn. I think it might have something to do with clipping but im not sure. Polygon and lines in

Solution 1:

This is how you can obtain it the opacity of everything outside a specific polygon (that could be a previously dynamically created). I just don't know how to get the drawing line outside to also have the opacity applied:

You can also check this demo SandBox: https://codesandbox.io/s/stackoverflow-60810389-fabric-js-362-vm92q

var canvas = new fabric.Canvas("canvas", {
  isDrawingMode: true
});

fabric.Image.fromURL("https://picsum.photos/500/350", function(img) {
  // add background image
  canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
    scaleX: canvas.width / img.width,
    scaleY: canvas.height / img.height
  });
});

var originalPolygon = new fabric.Polygon(
  [{ x: 0, y: 0 }, { x: 250, y: 0 }, { x: 220, y: 140 }, { x: 0, y: 140 }],
  {
    left: 10,
    top: 10,
    fill: "white",
    stroke: "red",
    strokeWidth: 2,
    selectable: false
  }
);

// An Overlay that covers the whole canvasvar overlayRect = new fabric.Rect({
  width: canvas.get("width"),
  height: canvas.get("height"),
  selectable: false,
  fill: "rgb(255, 255, 255, 0.8)"
});

// The clipPath object uses top,left,scale.... to position itself starting from the center of the object that is clipping// For more details check https://github.com/fabricjs/api-discussion/issues/1var clippingPolygon = new fabric.Polygon(originalPolygon.points, {
  left: -(overlayRect.get("width") / 2) - originalPolygon.get("left") * -1,
  top: -(overlayRect.get("height") / 2) - originalPolygon.get("top") * -1
});

var clipGroup = new fabric.Group([clippingPolygon], {
  inverted: true
});

overlayRect.clipPath = clipGroup;

// Comment adding of the orgiinalPolygon to see better the clipping effect
canvas.add(originalPolygon);
canvas.add(overlayRect);

canvas.renderAll();
body {
  font-family: sans-serif;
}
canvas {
  border: 2px solid #333;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script><divid="app"><canvasid="canvas"width="500"height="350"></canvas></div>

Post a Comment for "Setting Opacity To Canvas Fabricjs"