2012-12-18 147 views
4

以下是jsfiddle我们如何限制Fabric.js中画布对象的最大宽度和高度

我想在调整大小时限制对象的最大高度/宽度。

下面是代码:

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"></script> 
    </head> 
    <body> 
    <canvas id="c" width="300" height="300" style="border:1px solid #ccc"></canvas> 
    <script> 
     (function() { 

     var canvas = new fabric.Canvas('c'); 

     canvas.add(new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100 })); 
     canvas.add(new fabric.Rect({ width: 30, height: 30, fill: 'green', top: 50, left: 50 })); 


     })(); 
    </script> 
    </body> 
</html>​ 
+0

https://github.com/kangax/fabric.js/issues/167#issuecomment-7010429这里是说,我们需要用事件来实现它..我该怎么做呢? – syllogismos

+0

使用'mousemove','mouseup'和'mousedown'。 –

+0

说我想要设置红色正方形的最大高度,而不是上面例子中的蓝色正方形。我怎么做?你可以更具体一些,我如何处理这些mousemove事件在一个特定的画布对象? @RicardoLohmann – syllogismos

回答

8

当缩放织物目的,scaleX和scaleY属性被更新,以反映对象的新缩放大小。因此,缩放2倍时初始宽度为50的矩形的实际宽度将为100.

您需要做的是计算您的形状允许的最大比例,因为它的大小为maxHeight或maxWidth。这是通过将最大尺寸除以初始尺寸计算的。

下面是如何实现的最大尺寸的物体

var canvas = new fabric.Canvas("c"); 
var rect1 = new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100}); 
var rect2 = new fabric.Rect({ width: 30, height: 30, fill: 'green', top: 50, left: 50 }); 

// add custom properties maxWidth and maxHeight to the rect 
rect1.set({maxWidth:100,maxHeight:120}); 

canvas.observe("object:scaling", function(e){ 
    var shape = e.target 
    , maxWidth = shape.get("maxWidth") 
    , maxHeight = shape.get("maxHeight") 
    , actualWidth = shape.scaleX * shape.width 
    , actualHeight = shape.scaleY * shape.height; 

    if(!isNaN(maxWidth) && actualWidth >= maxWidth){ 
     // dividing maxWidth by the shape.width gives us our 'max scale' 
     shape.set({scaleX:maxWidth/shape.width}) 
    } 

    if(!isNaN(maxHeight) && actualHeight >= maxHeight){ 
     shape.set({scaleY:maxHeight/shape.height}) 
    } 

    console.log("width:" + (shape.width * shape.scaleX) + " height:" + (shape.height * shape.scaleY)); 
}); 
+0

你如何处理偏移量?现在调整大小的对象比我提供的最大宽度/高度大10px – Fabrizio

+0

Hello @cyberpantz如果可能,请通过我的问题:http://stackoverflow.com/questions/26500990/issue-with-object-while-restricting画布边界 – Innodel

2

与大多数面料的对象..一个例子,但你想要得到你的对象的比例,maxWidth你可以复制这个...为maxHeight反转它。

fabric.Image.fromURL(photo, function(image) { 
    //console.log(image.width, image.height); 
    var heightRatio = image.height/image.width; 
    var maxWidth = 100; 
    image.set({ 
    left: canvasDimensions.width/2,//coord.left, 
    top: canvasDimensions.height/2, //coord.top, 
    angle: 0, 
    width: maxWidth, 
    height: maxWidth * heightRatio 
    }) 
    //.scale(getRandomNum(minScale, maxScale)) 
    .setCoords(); 

    canvas.add(image); 
    }) 
+0

您拯救了我的一天!韩国社交协会。 –