0

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

页面截图:

网页

保存的图像::

在此处输入图像描述

4

1 回答 1

2

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

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/

希望这可以帮助 :)

于 2014-04-26T06:50:50.723 回答