Avoid overflow in clip area from canvas fabricjs

2019-04-16 20:17发布

问题:

i am using clip to define drawing area on canvas . when user moves inside object in out defined area then element are not visible but when i save canvas as image they are coming in picture . how can i avoid overflowing ? or restric elements move ??

page screen shot:

Saved image ::

回答1:

This can be done using two ways:

1) Clipping the the canvas area within a Rectangle

canvas.clipTo = function(ctx) {                     
    ctx.beginPath();
    var rect = new fabric.Rect({
            fill: 'red',
            opacity: 0,
            left: 0,
            top: 0,
            width: canvas.width,
            height: canvas.height
    });
    ctx.strokeStyle = 'black';
    rect.render(ctx);
    ctx.stroke();
}

2) Restrict objects to a rectangular boundary

constrainToBounds = function (activeObject) {
        if(activeObject)
        {
            var angle = activeObject.getAngle() * Math.PI/180,
            aspectRatio = activeObject.width/activeObject.height,
            boundWidth = getBoundWidth(activeObject),
            boundHeight = getBoundHeight(activeObject);
            if(boundWidth > bounds.width) {
                boundWidth = bounds.width;
                var targetWidth = aspectRatio * boundWidth/(aspectRatio * Math.abs(Math.cos(angle)) + Math.abs(Math.sin(angle)));
                    activeObject.setScaleX(targetWidth/activeObject.width);
                    activeObject.setScaleY(targetWidth/activeObject.width);
                    boundHeight = getBoundHeight(activeObject);
                }
                if(boundHeight > bounds.height) {
                    boundHeight = bounds.height;
                    var targetHeight = boundHeight/(aspectRatio * Math.abs(Math.sin(angle)) + Math.abs(Math.cos(angle)));
                    activeObject.setScaleX(targetHeight/activeObject.height);
                    activeObject.setScaleY(targetHeight/activeObject.height);
                    boundWidth = getBoundWidth(activeObject);
                }
                //Check constraints
                if(activeObject.getLeft() < bounds.x + boundWidth/2)
                    activeObject.setLeft(bounds.x + boundWidth/2);
                if(activeObject.getLeft() > (bounds.x + bounds.width - boundWidth/2))
                    activeObject.setLeft(bounds.x + bounds.width - boundWidth/2);
                if(activeObject.getTop() < bounds.y + boundHeight/2)
                    activeObject.setTop(bounds.y + boundHeight/2);
                if(activeObject.getTop() > (bounds.y + bounds.height - boundHeight/2))
                    activeObject.setTop(bounds.y + bounds.height - boundHeight/2);
            }
    }

We have used these in a tshirt application live - http://www.riaxe.com/html5-tshirt-designer-application/

Hope this helps :)