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

时间:2012-12-18 22:44:41

标签: javascript html5 canvas fabricjs

这是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>​

2 个答案:

答案 0 :(得分: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));
});

答案 1 :(得分: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);
  })