How to hide the overflow of photos in canvas?

*爱你&永不变心* 提交于 2019-12-12 00:34:45

问题


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



来源:https://stackoverflow.com/questions/29943533/how-to-hide-the-overflow-of-photos-in-canvas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!