如何只用一个 JavaScript 函数绘制任何规则形状

使用 JavaScript 绘制六边形

六边形有六个相等的边。如果我们想象我们的起点是六边形的中心,我们可以绕着这个点移动六次,在我们制作边的时候连接每个点。
让我们从创建带有2d 绘图上下文的 开始。对于这个例子,我们将画布的大小固定为 400 x 200 像素,并将中心点设置为(200, 100).
<canvas></canvas>
const canvas = document.querySelector("canvas");
canvas.width = 400;
canvas.height = 200;

const ctx = canvas.getContext("2d");
const cx = 200;
const cy = 100;

现在我们需要计算出围绕中心的点的 x(水平)和 y(垂直)位置,当与一条线连接时,将形成六个相等的边。为此,我们使用从中心到点的测量值(我们称之为半径)和与中心的方向角。
由于完整旋转有 360 度,我们想要创建六个点,所以我们可以划分 360/6 并且知道我们将每 60 度创建一个点。然而,对此有一个小小的警告——JavaScript 使用radiansrather than degrees. pi我一直记得的一件事是中的值radians是 180 度,或半个圆。所以(Math.PI*2)/6会给我们每一次轮换,radians 甚至更简单Math.PI/3。
接下来我们需要添加一点三角函数来找到每个点的 x 和 y 位置。对于 x 位置,我们可以使用总半径乘以cos(angle),对于 y 位置半径乘以sin(angle)。 让我们把它们放在一起,添加到上面的 JavaScript 代码中:
// set the radius of the hexagon
const radius = 50;

// move the canvas to the center position
ctx.translate(cx, cy);

for (let i = 0; i < 6; i++) {
  // calculate the rotation
  const rotation = (Math.PI / 3) * i;

  // for the first point move to
  if (i === 0) {
    ctx.moveTo(radius * Math.cos(rotation), radius * Math.sin(rotation));
  } else {
    // for the rest draw a line
    ctx.lineTo(radius * Math.cos(rotation), radius * Math.sin(rotation));
  }
}

// close path and stroke it
ctx.closePath();
ctx.stroke();

在这里插入图片描述

绘制任意边数的形状

假设我们想画一个三角形、一个正方形或一个八边形。在上面用于绘制六边形的函数中,我们需要修改的只是我们在循环中绘制线的次数for和每个点的角度。
让我们把它变成一个以中心点、半径和边数为参数的函数:
function drawShape(x, y, r, sides) {
  // move the canvas to the center position
  ctx.translate(x, y);

  for (let i = 0; i < sides; i++) {
    // calculate the rotation
    const rotation = ((Math.PI * 2) / sides) * i;

    // for the first point move to
    if (i === 0) {
      ctx.moveTo(r * Math.cos(rotation), r * Math.sin(rotation));
    } else {
      // for the rest draw a line
      ctx.lineTo(r * Math.cos(rotation), r * Math.sin(rotation));
    }
  }

  // close path and stroke it
  ctx.closePath();
  ctx.stroke();

  // reset the translate position
  ctx.resetTransform();
}

现在我们可以通过调整sides参数来绘制不同的形状:

drawShape(100, 100, 50, 3);
drawShape(225, 100, 50, 7);
drawShape(350, 100, 50, 4);

在这里插入图片描述

来源链接: link

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值