
You can build any polygon (hexagon, star, etc.) using Fabric.Polygon .
var myPoly = new fabric.Polygon(points, { stroke: 'red', left: 50, top: 50, strokeWidth: 2, strokeLineJoin: 'bevil' },false); canvas.add(myPoly);
You can calculate the vertex points of any regular polygon with the desired count like this:
// get the vertices of a hexagon with a radius of 30 var points=regularPolygonPoints(6,30); function regularPolygonPoints(sideCount,radius){ var sweep=Math.PI*2/sideCount; var cx=radius; var cy=radius; var points=[]; for(var i=0;i<sideCount;i++){ var x=cx+radius*Math.cos(i*sweep); var y=cy+radius*Math.sin(i*sweep); points.push({x:x,y:y}); } return(points); }
You can calculate the vertex points of any star with your desired number of spikes as follows:
// get the vertices of a hexagon with a radius of 30 var points=starPolygonPoints(5,50,25); function starPolygonPoints(spikeCount, outerRadius, innerRadius) { var rot = Math.PI / 2 * 3; var cx = outerRadius; var cy = outerRadius; var sweep = Math.PI / spikeCount; var points = []; var angle = 0; for (var i = 0; i < spikeCount; i++) { var x = cx + Math.cos(angle) * outerRadius; var y = cy + Math.sin(angle) * outerRadius; points.push({x: x, y: y}); angle += sweep; x = cx + Math.cos(angle) * innerRadius; y = cy + Math.sin(angle) * innerRadius; points.push({x: x, y: y}); angle += sweep } return (points); }
So, in general, for any desired geometric shape, you must calculate the vertices and transfer these vertices to Fabric.Polygon
Here is a sample code and demo:
body{ background-color: ivory; } #canvas{border:1px solid red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script> <canvas id="canvas" width=300 height=300></canvas>
markE
source share