Fabric.js - 绘制正八边形

时间:2017-03-14 08:55:00

标签: javascript fabricjs

我正在使用Fabric.js,我有以下代码来绘制六边形:

makeObject(originPoint, newPoint, canvasObject, properties) {

let width = Math.abs(newPoint.x - originPoint.x);
let height = 0;

if(this.shouldKeepProportion){
  height=width;
}else{
  height=Math.abs(newPoint.y - originPoint.y);
}

  width = (this.minWidth!=null && width<this.minWidth ? this.minWidth: width);
  height = (this.minHeight!=null && height<this.minHeight ? this.minHeight : height);

let sweep=Math.PI*2/6;
let points=[];
//generate points for 6 angles
for(let i=0;i<6;i++){
    let x=width*Math.cos(i*sweep);
    let y=height*Math.sin(i*sweep);
    points.push({x:x/2,y:y/1.75});
}

properties = {
    objectType: 'octagon',
    left: originPoint.x,
    top: originPoint.y,
    originX: 'left',
    originY: 'top',
    fill: 'rgba(0, 0, 0, 1.0)',
    width: width,
    height: height,
    originX: originPoint.x > newPoint.x ? 'right' : 'left',
    originY: originPoint.y > newPoint.y ? 'bottom' : 'top',
    flipX: originPoint.x > newPoint.x,
    stroke: 'rgba(0, 0, 0, 1.0)',
    strokeWidth: 1,
    strokeLineJoin: 'round',
    ...properties
};

return new fabric.fabric.Polygon(points, properties);
}

我想要的是一个正八边形,与六边形相同。如果我试图改变角/角的数量,我得到以下类型的八角形: enter image description here

我真正需要的是: enter image description here

请注意:我不需要它旋转或翻转或类似的东西,我需要它画在图片上。

感谢您的帮助!

编辑:工作JSFiddle:https://jsfiddle.net/42fb716n/

1 个答案:

答案 0 :(得分:1)

这应该这样做,使用Polygon()函数而不是Line(),因此它就像一个对象,而不是一组对象,所以它在你的绘图应用程序中工作,因为你有不同的属性单个和组对象:

&#13;
&#13;
var canvas = new fabric.Canvas('canvas');
var size = 150;
var side = Math.round((size * Math.sqrt(2)) / (2 + Math.sqrt(2)));
var octagon = new fabric.Polygon([
  {x:-side / 2, y:size / 2},
  {x:side / 2, y:size / 2},
  {x:size / 2, y:side / 2},
  {x:size / 2, y:-side / 2},
  {x:side / 2, y:-size / 2},
  {x:-side / 2, y:-size / 2},
  {x:-size / 2, y:-side / 2},
  {x:-size / 2, y:side / 2}], {
    stroke: 'red',
    left: 10,
    top: 10,
    strokeWidth: 2,
    strokeLineJoin: 'bevil'
},false);
canvas.add(octagon);
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="canvas" width=200 height=200></canvas>
&#13;
&#13;
&#13;

如果您还有其他需要,请告诉我。很乐意提供帮助!