p5.js入门学习-正多边形

93 阅读1分钟

beginShape()函数能够绘制出更复杂的形状,需要注意的是,当定义完成形状后,需要调用endShape()函数结束绘制。

vertex()函数是beginShape()中专门用于指定顶点的函数。

translate()、rotate()、scale()等转换函数以及其他绘图工具均不能与beginShape()一起使用。

本示例的自定义函数polygon()能够绘制任何正多边形,我们通过以下示例来了解以下吧。

function setup() {
  // 画布大小:720*400
  createCanvas(720, 400);
  noLoop();
}
function draw() {
  background(102);
  // 调用自定义函数 polygon(x, y, radius, npoints)
  polygon(width * 0.2, height * 0.5, 82, 3);
  polygon(width * 0.5, height * 0.5, 80, 20);
  polygon(width * 0.8, height * 0.5, 70, 7);
}
function polygon(x, y, radius, npoints) {
  // 计算两个顶点之间的角度
  let angle = TWO_PI / npoints;
  beginShape();
  // 注意循环是按照顶点和顶点之间的角度值自增的
  for (let a = 0; a < TWO_PI; a += angle) {
      // 我们把多边形的每一个顶点看成是找圆上的点,以此获得了以下计算公式
    let sx = x + cos(a) * radius;
    let sy = y + sin(a) * radius;
    // 指定顶点
    vertex(sx, sy);
  }
  endShape(CLOSE);
}
new p5();

p5js 开源社区 - 乐述云享 (aleshu.com)