5

这是jsfiddle

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

这是代码:

<!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>​
4

2 回答 2

9

缩放结构对象时,scaleX 和 scaleY 属性会更新以反映对象的新缩放大小。因此,当缩放 2x 时,初始宽度为 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));
});
于 2012-12-19T23:03:50.927 回答
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);
  })
于 2015-03-20T12:36:57.013 回答