简体   繁体   English

Fabric Js:如何仅以2个点(即左上角和右下角)以编程方式创建矩形?

[英]Fabric Js: How to Create Rectangle programatically with only 2 points that is Top Left Corner and Bottom Right Corner?

The rectangle can be created using top, left, width, height like this 可以使用上,左,宽,高这样创建矩形

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

Is it possible to create a rectangle by setting its aCoords top-left-corner and bottom-right-corner?Is there any way for creating Rectangle with only those two points? 是否可以通过设置其aCoords的左上角和右下角来创建矩形?有没有办法仅用这两个点来创建Rectangle?

For your rectangle, 对于您的矩形,

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

DEMO DEMO

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM