我们可以通过创建fabric.polygon的实例来创建polygon对象。多边形对象的特征可以是由一组连接的直线段组成的任何闭合形状。由于它是 fabricjs 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松自定义它。
语法new fabric.polygon( points: array, options: object )
参数points - 此参数接受一个array,它表示组成多边形对象的点数组。
选项(可选) - 此参数是一个对象,它为我们的目的。使用此参数可以更改与 polygon 对象相关的原点、描边宽度和许多其他属性。
示例 1:使用多边形绘制六边形让我们看一个代码示例,了解如何使用多边形绘制六边形。我们可以绘制多种类型的六边形,但是,在本例中我们将绘制正六边形。我们知道正六边形有六个相等的边。
<!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>drawing a hexagon using polygon</h2> <p>you can see a hexagon object has been added to the canvas</p> <canvas id=canvas></canvas> <script> // initiate a canvas instance var canvas = new fabric.canvas(canvas); canvas.setwidth(document.body.scrollwidth); canvas.setheight(250); // initiating the angle of the hexagon const a = (2 * math.pi) / 6; // initiating the radius of the circle const r = 50; // initiate a polygon object var hexagon = new fabric.polygon( [ { x: 50, y: 0 }, { x: 25, y: 43.30}, { x: -25, y: 43.301 }, { x: -50, y: 0}, { x: -25, y: -43.301}, { x: 25, y: -43.301 }, ], { stroke: red, left: 140, top: 10, strokewidth: 2, strokelinejoin: bevil, } ); // adding it to the canvas canvas.add(hexagon); </script></body></html>
示例2:使用polygon绘制六边形网格让我们看一个代码示例,看看如何创建六边形网格。我们可以简单地启动一个名为 drawhexagon(m,n) 的函数,其中 (m,n) 是六边形的中心点。每当调用此函数时,都会绘制六边形。我们还启动 drawgrid(width, height) 函数,该函数通过计算连续六边形的下一个中心的位置来绘制连续的六边形。
<!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>drawing a hexagonal grid using polygon</h2> <p>you can see that a hexagonal grid has been drawn</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 polygon object function drawhexagon(left, top) { var hexagon = new fabric.polygon( [ { x: 50, y: 0 }, { x: 25, y: 43.30}, { x: -25, y: 43.301 }, { x: -50, y: 0}, { x: -25, y: -43.301}, { x: 25, y: -43.301 }, ], { stroke: #eec33d, fill: #bb900c, strokewidth: 5, left: left, top: top } ); // adding it to the canvas canvas.add(hexagon); } // initiating the drawgrid function function drawgrid() { for (let y = 1; y < 4; y++) { drawhexagon(80*y,45*y) } for (let y = 1; y < 4; y++) { drawhexagon(80*y+160,45*y) } for (let y = 1; y < 4; y++) { drawhexagon(80*y+320,45*y) } } // calling drawgrid function drawgrid(); </script></body></html>
结论在本教程中,我们使用两个简单的示例来演示如何使用 fabricjs 使用 polygon 类绘制六边形网格。
以上就是fabric.js – 如何使用 polygon 类绘制六边形网格(蜂巢)的详细内容。