防止Fabric JS对象在边界外可见

时间:2017-04-19 11:15:19

标签: javascript html5-canvas fabricjs

我有2个矩形。当小矩形移动到较大的矩形之外时,我希望边界外的小矩形区域变得不可见。

如果一半的小矩形在里面,一半在外面。然后只有一半可见,这个example就是这样。

我怎样才能做到这一点?

My JSFiddle

(function() {
  var canvas = this.__canvas = new fabric.Canvas('canvas');
  fabric.Object.prototype.transparentCorners = false;

  // create a rectangle with a fill and a different color stroke
  var rect = new fabric.Rect({
    left: 50,
    top: 50,
    width: 150,
    height: 250,
    fill: 'transparent',
    stroke: 'rgba(34,177,76,1)',
    strokeWidth: 1
  });

  var rect2 = new fabric.Rect({
    left: 50,
    top: 50,
    width: 50,
    height: 50,
    fill: 'rgba(34,50,100,1)',
    stroke: 'rgba(34,177,76,1)',
    strokeWidth: 1
  });
  canvas.add(rect);
  canvas.add(rect2);
})();

这里的示例使用这种方式:

1 个答案:

答案 0 :(得分:1)

这可以通过以下方式实现,还有一个名为lodash

的额外库

(function() {
    var canvas = this.__canvas = new fabric.Canvas('canvas');
    fabric.Object.prototype.transparentCorners = false;
    // create a rectangle with a fill and a different color stroke
    var rect = new fabric.Rect({
        left: 50,
        top: 50,
        width: 150,
        height: 250,
        fill: 'transparent',
        stroke: 'rgba(34,177,76,1)',
        strokeWidth: 1
    });
    var rect2 = new fabric.Rect({
        left: 50,
        top: 50,
        width: 50,
        height: 50,
        fill: 'rgba(34,50,100,1)',
        stroke: 'rgba(34,177,76,1)',
        strokeWidth: 1,
        clipName: 'rect2',
        clipTo: function(ctx) {
            return _.bind(clip, rect2)(ctx)
        }
    });

    function d2R(deg) {
        return deg * (Math.PI / 180);
    }

    function clip_name(name) {
        return _(canvas.getObjects()).where({
            clipFor: name
        }).first()
    }

    function clip(ctx) {
        this.setCoords();
        var clipObj = clip_name(this.clipName);
        var scaleXTo1 = (1 / this.scaleX);
        var scaleYTo1 = (1 / this.scaleY);
        ctx.save();
        var ctxLeft = -(this.width / 2) + clipObj.strokeWidth;
        var ctxTop = -(this.height / 2) + clipObj.strokeWidth;
        var ctxWidth = clipObj.width - clipObj.strokeWidth;
        var ctxHeight = clipObj.height - clipObj.strokeWidth;
        ctx.translate(ctxLeft, ctxTop);
        ctx.scale(scaleXTo1, scaleYTo1);
        ctx.rotate(d2R(this.angle * -1));
        ctx.beginPath();
        ctx.rect(clipObj.left - this.oCoords.tl.x, clipObj.top - this.oCoords.tl.y, clipObj.width, clipObj.height);
        ctx.closePath();
        ctx.restore();
    }
    rect.set({
        clipFor: 'rect2'
    });
    canvas.add(rect);
    canvas.add(rect2);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.9/fabric.min.js"></script>
<canvas id="canvas" width="800" height="600"></canvas>