从圆中创建多边形
create polygon out of a circle
所以我一直在尝试通过计算这个圆上的点然后将它们连接起来,从一个圆中创建具有一定数量顶点的多边形。
问题是:处理不会将顶点连接在一起。
从一开始,我使用的方法并不是最优的,我没有计算点然后将顶点放在这些点上,而是使用了 rotate() 函数。
我知道有一个用sin()和cos()计算圆外点的公式,但是我想不起来了。
无论如何,这是代码
translate(width/2,height/2);
ellipse(0,0,250,250);
let numPoints = 3;
beginShape();
for (let i = 0; i < numPoints; i ++){
vertex(-250/2,0);
ellipse(-250/2,0,10);
rotate(TWO_PI/numPoints)
}
endShape();
感谢您的帮助!
查看以获得详细解释,否则:
x = cos(angle) * radius
y = sin(angle) * radius
有关详细信息,另请参阅 atan2
p5.js 附带 Regular Polygon example 顺便说一句:
// example source: https://p5js.org/examples/form-regular-polygon.html
function setup() {
createCanvas(720, 400);
}
function draw() {
background(102);
push();
translate(width * 0.2, height * 0.5);
rotate(frameCount / 200.0);
polygon(0, 0, 82, 3);
pop();
push();
translate(width * 0.5, height * 0.5);
rotate(frameCount / 50.0);
polygon(0, 0, 80, 20);
pop();
push();
translate(width * 0.8, height * 0.5);
rotate(frameCount / -100.0);
polygon(0, 0, 70, 7);
pop();
}
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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
所以我一直在尝试通过计算这个圆上的点然后将它们连接起来,从一个圆中创建具有一定数量顶点的多边形。 问题是:处理不会将顶点连接在一起。
从一开始,我使用的方法并不是最优的,我没有计算点然后将顶点放在这些点上,而是使用了 rotate() 函数。
我知道有一个用sin()和cos()计算圆外点的公式,但是我想不起来了。
无论如何,这是代码
translate(width/2,height/2);
ellipse(0,0,250,250);
let numPoints = 3;
beginShape();
for (let i = 0; i < numPoints; i ++){
vertex(-250/2,0);
ellipse(-250/2,0,10);
rotate(TWO_PI/numPoints)
}
endShape();
感谢您的帮助!
查看
x = cos(angle) * radius
y = sin(angle) * radius
有关详细信息,另请参阅 atan2
p5.js 附带 Regular Polygon example 顺便说一句:
// example source: https://p5js.org/examples/form-regular-polygon.html
function setup() {
createCanvas(720, 400);
}
function draw() {
background(102);
push();
translate(width * 0.2, height * 0.5);
rotate(frameCount / 200.0);
polygon(0, 0, 82, 3);
pop();
push();
translate(width * 0.5, height * 0.5);
rotate(frameCount / 50.0);
polygon(0, 0, 80, 20);
pop();
push();
translate(width * 0.8, height * 0.5);
rotate(frameCount / -100.0);
polygon(0, 0, 70, 7);
pop();
}
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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>