Kasey McCurdy
Kasey McCurdy

Reputation: 59

Use a group as a mask in fabric.js

I want to create a group that is 300px wide and 200px high, and then load a few things inside that group. When I load images in that are larger than the group dimensions, it bleeds outside the group. I'd love to "crop" the image (similar to a CSS overflow:hidden property).

Is this possible?

Upvotes: 1

Views: 1410

Answers (1)

invernomuto
invernomuto

Reputation: 10211

To accomplish your task you should use the clipTo function on your image, the clipTo function on a group already has an open bug, btw you can work around there, by transpose the dimension and the position of your group to clipTo function:

clipTo :Function § Function that determines clipping of an object (context is passed as a first argument) Note that context origin is at the object's center point (not left/top corner)

Take a look to official demo, then after the clip operation on your image you can add it to a group(run below script to see an example).

var canvas = window.__canvas = new fabric.Canvas('c');
var path = 'http://fabricjs.com/lib/pug.jpg';

var _img = new Image();
_img.onload = function(img) {
  var dog = new fabric.Image(_img, {

    left: 100,
    top: 100,
    width: 300,
    height: 300,
    selectable: false,
    clipName: 'dog',
    clipTo: function(ctx) {
      
      ctx.rect(0, 0, 50, 50);
    }
  });

  var group = new fabric.Group([dog], {
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    borderColor: 'black',
  });

  canvas.add(group);
};
_img.src = path;


canvas.renderAll();
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.13/fabric.min.js"></script>
<canvas id="c" height="300" width="300" style="border:1px dashed #333;"></canvas>

Upvotes: 1

Related Questions