p5.js入门学习-星星

144 阅读1分钟

本示例将继续使用beginShape()函数来绘制复杂图形:星星。

添加图片注释,不超过 140 字(可选)

function setup() {
  // 画布大小:720*400
  createCanvas(720, 400);
  noLoop();
}
function draw() {
  background(102);
  // 调用自定义函数:start(x, y, radius1, radius2, npoints)
  star(width * 0.2, height * 0.5, 5, 70, 3);
  star(width * 0.5, height * 0.5, 80, 100, 40);
  star(width * 0.8, height * 0.5, 30, 70, 5);
}
// (x, y)为图形中心坐标
// radius1,radius2分别是星星的内外顶点所在圆的半径,但并不代表radius1一定是内圆/外圆,仅仅只是表达起来更具体,这边才这么解释的
// npoints是星星的顶点个数
function star(x, y, radius1, radius2, npoints) {
  // 计算顶点之间的角度
  let angle = TWO_PI / npoints;
  // 内顶点与外顶点之间需要有一个旋转角度
  let halfAngle = angle / 2.0;
  beginShape();
  // 循环是以顶点两点之间的角度来作为自增参数的
  for (let a = 0; a < TWO_PI; a += angle) {
    // 外顶点计算公式,把外顶点想象是圆上的一点就可以理解了
    let sx = x + cos(a) * radius2;
    let sy = y + sin(a) * radius2;
    vertex(sx, sy);
    // 内顶点计算公式
    sx = x + cos(a + halfAngle) * radius1;
    sy = y + sin(a + halfAngle) * radius1;
    vertex(sx, sy);
  }
  endShape(CLOSE);
}
new p5();

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