【问题标题】:Fabric.js - Draw regular octagonFabric.js - 绘制正八边形
【发布时间】:2017-03-16 04:45:00
【问题描述】:

我正在使用 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);
}

我想要的是一个正八边形,和六边形一样。如果我尝试更改角/角度的数量,我会得到以下类型的八角形:

我真正需要的是:

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

感谢您的帮助!

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

【问题讨论】:

标签: javascript fabricjs


【解决方案1】:

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

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);
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="canvas" width=200 height=200></canvas>

如果您还需要什么,请告诉我。乐于助人!

【讨论】:

  • 非常感谢@Tim,但是可以使用 Polygon() 函数代替 Line() 吗?原因是因为我需要它像单个对象,而不是一组对象,因为在我的绘图应用程序中,单个对象和组对象具有不同的属性。
  • jsfiddle.net/42fb716n 我的意思是这样的 JSFiddle
  • 我只是更新我的答案。希望它更符合您的喜好。
  • 知道了!我稍微修改了代码如下:var sizeX = width; var sideX = Math.round((width* Math.sqrt(2)) / (2 + Math.sqrt(2))); var sizeY = height; var sideY= Math.round((height* Math.sqrt(2)) / (2 + Math.sqrt(2))); let points=[ {x:-sideX / 2, y:sideY }, {x:sideX / 2, y:sideY }, {x:sizeX /2, y:sizeY / 6}, {x:sizeX /2, y:-sizeY / 6}, {x:sideX / 2, y:-sideY }, {x:-sideX / 2, y:-sideY}, {x:-sizeX /2, y:-sizeY / 6}, {x:-sizeX /2, y:sizeY / 6}, ];
  • @TimHarker 谢谢蒂姆,我刚刚想通了,现在可以了。祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2021-12-28
  • 2015-07-30
  • 1970-01-01
  • 2011-12-30
相关资源
最近更新 更多