Search code examples
javascripthtmlfabricjscliptobounds

FabricJS ClipTo Issue for multiple objects like group


My code is

canvas.clipTo = function (ctx) {

    ctx.beginPath();
    for (var i = 0; i < totalPrintArea; i++) {
        ctx.save();
        ctx.fillStyle = 'rgba(51,51,51,0)';
        ctx.rect(clipLft[i], clipTp[i], clipW[i], clipH[i], 'rgba(51,51,51,1)', clipRtn[i]);
        ctx.stroke();
        ctx.restore();
    }

    ctx.closePath();
    ctx.clip();
    canvas.calcOffset();
};
canvas.renderAll();

I am taking values from the red dotted box and apply to clip where multiple masks are generating.

My issue is its taking all properties but not rotation for all.

I want to rotate all the rectangles.

I just get some code to change the rotation for the clip like ctx.rotate(50); but will not work as I want to make all rotate with their own values

Please guide me for the same.

no description


Solution

  • On the original fabricJS github project I saw the comment: https://github.com/kangax/fabric.js/issues/932#issuecomment-27223912

    and decided that I need to prevent making ctx.beginPath all the time:

    canvas.clipTo = function(ctx) { 
    var skip = false;
    // Workaround to make possible 
    // making clipTo with 
    // fabric.Group 
    var oldBeginPath = ctx.beginPath;
    ctx.beginPath = function() {
    if (!skip) {
      oldBeginPath.apply(this, arguments);
      skip = true;
      setTimeout(function() {
        skip = false;
      }, 0);
    }
    }
    group.render(ctx)
    };
    

    You can see my workaround to the problem described: https://jsfiddle.net/freelast/6o0o07p7/

    The workaround is not perfect, but hope it will help somebody.