How to hide the overflow of photos in canvas?

2019-09-04 02:11发布

问题:

I am trying making a photo frame pattern on canvas. In which I want to put two, three or maybe more photos under an overlay frame. Where few parts of the overlay frame are transparent.

If I upload photo1 into first section of frame its visible into second section also and uploading photo2 into section two is also visible into first section. Depending on which photo is uploaded first or edited at last is overlapping the other photo.

I want to know how to hide the overflow of photo so it should not be visible into other sections. How can I achieve this?

I have done this so far:

canvas.on({
    'object:moving': onChange,
    'object:scaling': onChange,
    'object:rotating': onChange,
});

function onChange(options) {
    options.target.setCoords();
    canvas.forEachObject(function (obj) {
        if (obj === options.target)
            return;


        if (obj.id != 'cover1' && obj.id != 'cover2')
            return;


        if (options.target.intersectsWithObject(obj)) {

           // Hide this portion

            canvas.renderAll();
        }

    });
}

Kindly provide me the best solution

回答1:

You need to apply a clipTo() method onto the image.

var canvas;

$(function(){
    canvas = window._canvas = new fabric.Canvas('canvas');
    var radius = 200;
    fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {
      img.scale(0.5).set({
        left: 250,
        top: 250,
        angle: -15,
        clipTo: function (ctx) {
          ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
        }
      });
      canvas.add(img).setActiveObject(img);
    });
});

This fiddle show the technique

Fiddle