首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免画布fabricjs中的剪辑区域溢出

避免画布fabricjs中的剪辑区域溢出
EN

Stack Overflow用户
提问于 2013-09-05 17:15:47
回答 1查看 2.1K关注 0票数 0

我正在使用clip在画布上定义绘图区域。当用户在外部定义的区域内移动对象时,元素是不可见的,但当我将画布保存为图像时,它们将进入图片。如何避免溢出?或者restric元素移动??

页面截图:

保存的图像::

EN

回答 1

Stack Overflow用户

发布于 2014-04-26 14:50:51

这可以使用两种方法来完成:

1)在矩形内裁剪画布区域

代码语言:javascript
复制
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)将对象限制为矩形边界

代码语言:javascript
复制
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);
            }
    }

我们已经在一个T恤应用程序live - http://www.riaxe.com/html5-tshirt-designer-application/中使用了它们

希望这能有所帮助:)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18632358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档