【问题标题】:FabricJS ClipTo Issue for multiple objects like group多个对象(如组)的 FabricJS ClipTo 问题
【发布时间】:2014-04-24 08:51:17
【问题描述】:

我的代码是

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();

我从红色虚线框中获取值并应用于生成多个蒙版的剪辑。

我的问题是它获取所有属性,但不是全部旋转。

我想旋转所有的矩形。

我只是得到一些代码来改变剪辑的旋转,比如ctx.rotate(50);,但我想让所有代码都用自己的值旋转,所以它不起作用

请指导我。

【问题讨论】:

  • 请查看以下相同对象的具体代码。clipTo = function (ctx) { ctx.rect (x, y, width, height);我想为矩形添加旋转属性,而不是像 ctx.rotate(50) 这样的 ctx 对我不起作用我想要像 ctx.rect (x, y, width, height, rotate);
  • 请指导我
  • 你可以看看这个问题的答案,有一种转换角度的方法stackoverflow.com/questions/16437696/…

标签: javascript html fabricjs cliptobounds


【解决方案1】:

在原fabricJS github项目上看到评论:https://github.com/kangax/fabric.js/issues/932#issuecomment-27223912

并决定我需要一直阻止制作 ctx.beginPath:

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)
};

您可以查看我对所描述问题的解决方法: https://jsfiddle.net/freelast/6o0o07p7/

解决方法并不完美,但希望对某人有所帮助。

【讨论】:

    【解决方案2】:

    我尝试过使用Andrey's answer,但尽管有一些有趣的地方,但还是没用。

    如果您尝试将画布剪辑到单个对象(例如圆形或矩形),您可以简单地这样做:

    canvas.clipTo = function(ctx) {
        shape.render(ctx); //shape is a circle, for instance
    }
    

    但是,正如 Kienz 和 butch2k 在aforementioned comment on GitHub 中所解释的那样,问题是您不能将此解决方案用于组。特别是,如果您使用以下 sn-p:

    canvas.clipTo = function(ctx) {
        group.render(ctx);
    }
    

    您只会看到组中的一个对象用于剪辑。

    问题是由于render 方法导致的,该方法为组中的每个对象调用ctx.beginPath()ctx.closePath()。而且因为只有最后几个 beginPath-closePath 调用会影响剪辑,所以您需要一些解决方法。

    因此,在我的解决方案中,我临时重新定义了 ctx.closePathctx.beginPath 方法(在将它们存储在另外两个名为 oldBeginPatholdClosePath 的临时变量中之后),以便它们什么都不做。然后我在开始时调用oldBeginPath,在渲染组中的所有对象后我调用oldClosePath

    现在,这里是(工作的)sn-p:

    canvas.clipTo = function(ctx) {
        var oldBeginPath = ctx.beginPath;
        var oldClosePath = ctx.closePath;
    
        ctx.beginPath = function() {}
        ctx.closePath = function() {}
    
        oldBeginPath.apply(ctx);
        group.forEachObject(function(shape){
            shape.render(ctx);
        });
        oldClosePath.apply(ctx);
    
        ctx.beginPath = oldBeginPath;
        ctx.closePath = oldClosePath;
    };
    

    希望这将节省某人将来的业余时间。

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2016-01-12
      • 2021-01-04
      • 2016-05-15
      • 2020-11-02
      相关资源
      最近更新 更多