Multiple clipping areas on Fabric.js canvas

前端 未结 7 1532
一生所求
一生所求 2020-11-28 04:26

For making Photo Collage Maker, I use fabric js which has an object-based clipping feature. This feature is great but the image inside that clipping region cannot be scaled,

7条回答
  •  死守一世寂寞
    2020-11-28 05:08

    As I tested all fiddles above they have one bug. It is when you will flip X and Y values together, clipping boundaries will be wrong. Also, in order not doing all calculations for placing images into the right position, you need to specify originX='center' and originY='center' for them.

    Here is a clipping function update to original code from @natchiketa

    var clipByName = function (ctx) {
        var clipRect = findByClipName(this.clipName);
        var scaleXTo1 = (1 / this.scaleX);
        var scaleYTo1 = (1 / this.scaleY);
        ctx.save();
        ctx.translate(0,0);
    
        //logic for correct scaling
        if (this.getFlipY() && !this.getFlipX()){
          ctx.scale(scaleXTo1, -scaleYTo1);
        } else if (this.getFlipX() && !this.getFlipY()){
          ctx.scale(-scaleXTo1, scaleYTo1);
        } else if (this.getFlipX() && this.getFlipY()){
          ctx.scale(-scaleXTo1, -scaleYTo1);
        } else {
            ctx.scale(scaleXTo1, scaleYTo1);
        }
        //IMPORTANT!!! do rotation after scaling
        ctx.rotate(degToRad(this.angle * -1));
        ctx.beginPath();
        ctx.rect(
            clipRect.left - this.left,
            clipRect.top - this.top,
            clipRect.width,
            clipRect.height
        );
        ctx.closePath();
        ctx.restore();
    }
    

    Please check the updated fiddle

提交回复
热议问题