eulercode
eulercode

Reputation: 1157

Fabric js clip object to background image

I am working on fabric js and I have encountered a problem where i have to clip user added object (text, image, svg etc) to background image set in canvas. The background image could be png or svg(with multiple path). The background image is of non-uniform shape, such as leaf, shirt etc.

How could it be done?

Upvotes: 4

Views: 3526

Answers (1)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('https://upload.wikimedia.org/wikipedia/commons/a/a2/Litchi_chinensis_leaf.png',
  function(img){
img.scale(0.3);
canvas.setBackgroundImage(img);
canvas.renderAll();
  }
);

var rect = new fabric.Rect({
  width:80, height:100, fill:'red',
  globalCompositeOperation: 'source-atop',
  top: 100
});
canvas.add(rect);

var circle = new fabric.Circle({
  radius:80, height:100, fill:'blue',
  globalCompositeOperation: 'source-atop'
});
canvas.add(circle);
circle.center().setCoords();
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='canvas' width="500" height="400" style="border:#000 1px solid;"></canvas>

This snippet shows you what is doable. Is not easy to clip with an "image". What you can do is use globalCompositeOperation as i show you.

As you see rect and circle are visible only over the background and not outside.

If you want using another value other than "source-atop" you can obtain different effects. With "source-in" the background will be transparent and will serve the only porpouse of "clipping" the area

Upvotes: 5

Related Questions