我使用剪辑在画布上定义绘图区域。当用户在定义区域内的对象内部移动时,元素不可见但是当我将画布保存为图像时,它们会进入图片。我怎么能避免溢出?或限制元素移动??
页面截图:
已保存的图片::
答案 0 :(得分: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/
希望这会有所帮助:)