2012-12-18 140 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

您拯救了我的一天!韓國社交協會。 –