就像我们可以指定位置、颜色一样,画布中矩形对象的不透明度和尺寸,我们还可以设置矩形对象的填充。这可以通过使用 padding 属性来完成。
语法new fabric.rect({ padding : number }: object)
参数选项(可选) - 此参数是一个对象,它为我们的矩形提供额外的自定义。使用此参数,可以更改与 padding 为属性的对象相关的属性,例如颜色、光标、描边宽度和许多其他属性。
选项键填充 - 此属性接受数字值。指定的值决定矩形对象与其控制边框之间的距离。
示例 1默认外观 不使用padding
让我们看一个代码示例,它在不使用padding属性时显示矩形对象的外观。正如我们所看到的,对象与其周围的控制边界之间没有空间。这意味着矩形与其控制边框之间的填充为零。
<!doctype html><html><head> <!-- adding the fabric js library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script></head><body> <h2>default appearance when padding is not used</h2> <p>you can select the rectangle to see there is no space between the object and its controlling borders.</p> <canvas id="canvas"></canvas> <script> // initiate a canvas instance var canvas = new fabric.canvas("canvas"); canvas.setwidth(document.body.scrollwidth); canvas.setheight(250); // initiate a rectangle object var rect = new fabric.rect({ left: 55, top: 90, width: 170, height: 70, fill: "#ffb347", stroke: "#191970", strokewidth: 5, }); // add it to the canvas canvas.add(rect); </script></body></html>
示例将 padding 属性作为键传递
在此示例中,我们将 padding 属性作为键传递值7。这个表示矩形对象与其所有对象之间的距离为 7px控制边界。
<!doctype html><html><head> <!-- adding the fabric js library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script></head><body> <h2>passing padding property as key</h2> <p>you can select the rectangle to see the padding between the object and its controlling borders.</p> <canvas id="canvas"></canvas> <script> // initiate a canvas instance var canvas = new fabric.canvas("canvas"); canvas.setwidth(document.body.scrollwidth); canvas.setheight(250); // initiate a rectangle object var rect = new fabric.rect({ left: 55, top: 90, width: 170, height: 70, fill: "#ffb347", stroke: "#191970", strokewidth: 5, padding: 7, }); // add it to the canvas canvas.add(rect); </script></body></html>
以上就是如何使用 fabricjs 设置矩形的填充?的详细内容。
