【问题标题】:Fabric Js: How to Create Rectangle programatically with only 2 points that is Top Left Corner and Bottom Right Corner?Fabric Js:如何以编程方式创建矩形,只有左上角和右下角两个点?
【发布时间】:2018-08-28 00:14:19
【问题描述】:

可以像这样使用顶部、左侧、宽度、高度来创建矩形

var rect = new fabric.Rect({
   left: 50,
   top: 50,
   width: 50,
   height: 50,
   fill: 'rgba(255,127,39,1)',
});

是否可以通过设置它的 aCoords 左上角和右下角来创建一个矩形?有没有办法只用这两个点创建矩形?

【问题讨论】:

    标签: javascript fabricjs


    【解决方案1】:

    对于你的矩形,

    width = difference between top-left x and right-bottom x,
    height = difference between top-left y and right-bottom y.
    

    演示

    var canvas = new fabric.Canvas('c');
    
    function getValue(id) {
      return document.getElementById(id).value
    }
    
    function r() {
      return Math.floor(Math.random() * 255)
    }
    
    function getColor() {
      return 'rgb(' + r() + "," + r() + "," + r() + ')';
    }
    
    function addRect() {
      var tlx = getValue('tlx'),
        tly = getValue('tly'),
        brx = getValue('brx'),
        bry = getValue('bry');
      if (tlx == '' || tly == '' || brx == '' || bry == '') {
        alert('Enter all values');
        return false;
      }
      var width = Math.abs(+tlx - +brx),
        height = Math.abs(+tly - +bry);
    
      var rect = new fabric.Rect({
        left: +tlx,
        top: +tly,
        width: width,
        height: height,
        fill: getColor()
      });
      canvas.add(rect);
    }
    canvas{
     border: 1px solid #000;
    }
    <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
    Top-left x: <input type='number' min="0" max="300" id='tlx'><br>
    Top-left y: <input type='number' min="0" max="300" id='tly'><br>
    Bottom-Right x: <input type='number' min="0" max="300" id='brx'><br>
    Bottom-Right x: <input type='number' min="0" max="300"id='bry'><br>
    <button onclick='addRect()'>Add</button>
    <canvas id="c" width="400" height="300"></canvas>

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多