【问题标题】:Avoid overflow in clip area from canvas fabricjs避免画布fabricjs的剪辑区域溢出
【发布时间】:2013-09-09 01:17:14
【问题描述】:

我正在使用剪辑在画布上定义绘图区域。当用户在外部定义区域内移动对象时,元素不可见,但是当我将画布保存为图像时,它们会出现在图片中。我怎样才能避免溢出?还是限制元素移动??

页面截图:

保存的图像::

【问题讨论】:

  • 您好,我也有同样的问题,请问您解决了吗?

标签: jquery html css canvas fabricjs


【解决方案1】:

这可以通过两种方式完成:

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

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) 将对象限制在矩形边界内

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 恤应用程序中使用了这些 - http://www.riaxe.com/html5-tshirt-designer-application/

希望这会有所帮助:)

【讨论】:

  • 你的工具看起来真的很棒而且更先进!!我正在从事类似的项目,并且已经完成了你项目提供的 70%。但不幸的是,由于客户的一些问题,我停止了这方面的工作。你们都做得很好:)
  • 感谢您的项目,祝您一切顺利。
  • 很好的代码,可以分享一下产品定制的代码吗?或者只是指导我创建自定义产品设计师。
猜你喜欢
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 2013-09-29
  • 2013-02-08
  • 1970-01-01
相关资源
最近更新 更多