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

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>

在这里提到我们需要通过事件来实现它...我该怎么做? - syllogismos
使用 mousemovemouseupmousedown - Ricardo Alvaro Lohmann
我想在上面的例子中将红色正方形的最大高度设置为特定值,而不是蓝色正方形。我该怎么做?你能更具体地说明一下吗?我如何处理特定画布对象上的mousemove事件?@RicardoLohmann - syllogismos
@RicardoLohmann,根据此链接http://fabricjs.com/events/,事件应该是object:scaling。 - syllogismos
2个回答

9

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

你需要做的是找出给定最大高度或最大宽度的形状允许的最大比例。这是通过将最大尺寸除以初始尺寸来计算的。

以下是如何为对象实现最大尺寸的示例

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));
});

你如何处理偏移量?现在,所有调整大小的对象都比我提供的最大宽度/高度多10像素。 - Fabrizio
你好@cyberpantz,如果可能的话,请查看我的问题:http://stackoverflow.com/questions/26500990/issue-with-object-while-restricting-it-to-canvas-boundary - Innodel

2

适用于大多数布料物品.. 但您想获得对象的比例,对于最大宽度,您可以复制此... 对于最大高度,请反转它。

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);
  })

你救了我的一天!谢谢。 - Diego Borges

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接