How to make a hole in fabricjs polygon

2019-08-12 18:26发布

问题:

I want to make a hole inside of polygon with fabricjs. I can make it using normal html5 canvas with counter-clockwise as shown below, but I would prefer to make it using fabricjs. Does anyone know how to implement the attached image using 'fabriicjs'?

Like this:

回答1:

Here's one way to draw a cutout-polygon onto FabricJS:

AFAIK, FabricJS does not yet support the compositing necessary to create cutouts from its polygons, so here's a workaround.

  1. Draw the cutout polygon onto an html5 canvas. For example

    • Draw the polygon from your specified points.
    • Set .globalCompositeOperation='destination-out'. This will cause all new drawings to act as an "eraser" and will cut out any existing pixels under the new drawings.
    • Draw the cutout from your specified points.
  2. Use the html5 canvas as an image source for a new Fabric.Image.

    // Create your polygon with transparent cuts on this html5 canvas
    // Use destination-out compositing to "punch holes" in your polygon
    var html5canvas=document.getElementById('myhtml5CanvasElement');
    
    // then use the html5 canvas as an image source for a new Fabric.Image
    var c=new Fabric.Image(html5Canvas);