Fabric.js 怎么画一个正六边形??

最近开发一个画板,有一个功能是在画板上画一个可拉动大小的正六边形;
效果如图:
图片描述

我自己用的Fabric.js 库,其它的图形还好,但这个六边形真的有点难画啊;
我自己尝试了几次都失败了;

canvas = new fabric.Polygon([],{
    top: y,
    left:x,
    width: Math.sqrt(Math.pow(height, 2) + Math.pow(height / 2.0, 2)),
    height: height,
    stroke: drawColor,
    strokeWidth: drawWidth,
    fill: "rgba(255,255,255,0)"
});

对于fabric.Polygon()里面那个[],应该怎么计算呢?
求解~~~~

阅读 4.1k
2 个回答
// 计算半径,边长
const R = Math.sqrt((mouseTo.x - mouseFrom.x) * (mouseTo.x - mouseFrom.x) + (mouseTo.y - mouseFrom.y) * (mouseTo.y - mouseFrom.y)) / 2;
// 6条边的坐标点(60是六边形的内角度数)
const points = Array.from({ length: 6 }).map((item, index) => {
    return {
        x: Math.cos(60 * index / 180 * Math.PI) * R,
        y: Math.sin(60 * index / 180 * Math.PI) * R
    }
});

我补上全部代码,怕有的朋友也遇到我们问题:

    let height = this.mouseTo.y - this.mouseFrom.y;
    // 计算半径,边长
    const R = Math.sqrt((this.mouseTo.x - this.mouseFrom.x) * (this.mouseTo.x - this.mouseFrom.x) + (this.mouseTo.y - this.mouseFrom.y) * (this.mouseTo.y - this.mouseFrom.y)) / 2;
    // 6条边的坐标点(60是六边形的内角度数)
    const points = Array.from({ length: 6 }).map((item, index) => {
        return {
            x: Math.cos(60 * index / 180 * Math.PI) * R,
            y: Math.sin(60 * index / 180 * Math.PI) * R
        }
    });
canvasObject = new fabric.Polygon(points,{
    top: this.mouseFrom.y,
    left: this.mouseFrom.x,
    width: Math.sqrt(Math.pow(height, 2) + Math.pow(height / 2.0, 2)),
    height: height,
    stroke: this.drawColor,
    strokeWidth: this.drawWidth,
    fill: "rgba(255,255,255,0)"
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题