3

How can I use clipTo with an image or SVG? I want to restrict any objects from going beyond the SVG shape outline / image outline.

I'm trying to accomplish something similar to this OP, however the responses did not seem clear to me how to accomplish this.

I can use clipTo with regular a shape, for example:

        var circle = new fabric.Circle({
            radius: 150,
            stroke: '#f55',
            fill: "transparent",
            top: 50,
            left: 50
        });
        circle.selectable = false;
        canvas.add(circle); 
        canvas.clipTo = function (ctx) {
            circle.render(ctx);
        };

See this fiddle for working example: http://jsfiddle.net/o9f4dqjn/1/

However I can't get this to work with an image. Is this possible?

Community
  • 1
  • 1
Rivka
  • 2,172
  • 10
  • 45
  • 74

1 Answers1

2

Although this solution does not use clipTo, it works.

From: https://github.com/kangax/fabric.js/issues/2313

And my modified working fiddle: http://jsfiddle.net/w396uhnv/

Basically you need to set the background image, and then set yourobject.globalCompositeOperation = 'source-atop'; on the object.

Note, the background image needs to have a transparent background, but non-transparent fill.


I could get clipTo method to work with SVG only (not an image):

        fabric.loadSVGFromURL('http://fabricjs.com/assets/23.svg', function (objects, options) {
            var shape = fabric.util.groupSVGElements(objects, options); 
            canvas.clipTo = function (ctx) {
                shape.render(ctx);
            };
            canvas.renderAll();
        });

Fabric.js Clip Canvas (or object group) To Polygon

Community
  • 1
  • 1
Rivka
  • 2,172
  • 10
  • 45
  • 74