Multiple clipping areas on Fabric.js canvas

前端 未结 7 1541
一生所求
一生所求 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 04:56

    I have tweaked the solution by @natchiketa as the positioning of the clip region was not positioning correctly and was all wonky upon rotation. But all seems to be good now. Check out this modified fiddle: https://jsfiddle.net/PromInc/ZxYCP/

    The only real changes were made in the clibByName function of step 3 of the code provided by @natchiketa. This is the updated function:

    var clipByName = function (ctx) {
        this.setCoords();
    
        var clipRect = findByClipName(this.clipName);
    
        var scaleXTo1 = (1 / this.scaleX);
        var scaleYTo1 = (1 / this.scaleY);
        ctx.save();
    
        var ctxLeft = -( this.width / 2 ) + clipRect.strokeWidth;
        var ctxTop = -( this.height / 2 ) + clipRect.strokeWidth;
        var ctxWidth = clipRect.width - clipRect.strokeWidth + 1;
        var ctxHeight = clipRect.height - clipRect.strokeWidth + 1;
    
        ctx.translate( ctxLeft, ctxTop );
    
        ctx.rotate(degToRad(this.angle * -1));
        ctx.scale(scaleXTo1, scaleYTo1);
        ctx.beginPath();
    
        ctx.rect(
            clipRect.left - this.oCoords.tl.x,
            clipRect.top - this.oCoords.tl.y,
            ctxWidth,
            ctxHeight
        );
        ctx.closePath();
        ctx.restore();
    }
    

    Two minor catches I found:

    1. Adding a stroke to the clipping object seems to throw things off by a few pixels. I tried to compensate for the positioning, but then upon rotation, it would add 2 pixels to the bottom and right sides. So, I've opted to just remove it completely.
    2. Once in a while when you rotate the image, it will end up with a 1px spacing on random sides in the clipping.

提交回复
热议问题