p5.js | beginShape()函数
p5.js 中的beginShape()函数用于绘制更复杂的形状。指定此函数开始记录将用于绘制形状的顶点。必须调用endShape()函数来结束录制并完成形状。
调用beginShape()函数后,应使用vertex()命令指定一系列顶点。形状使用当前描边颜色勾勒,并用当前填充颜色填充。有一个可选参数可以定义为使用要绘制的形状类型。
绘制的形状不适用于translate() 、 rotate()和scale()等转换函数。此外,不能通过 beginShape()使用其他形状。
句法:
beginShape( [kind] )
参数:此函数接受一个如上所述和如下所述的参数:
- kind:是一个常数,可以用来改变这个函数绘制的形状的种类。它可以有 POINTS、LINES、TRIANGLES、TRIANGLE_FAN、TRIANGLE_STRIP、QUADS、QUAD_STRIP 或 TESS 的值。它是一个可选参数。
以下示例说明了 p5.js 中的beginShape()函数:
示例 1:
let currMode;
function setup() {
createCanvas(500, 300);
textSize(18);
let shapeModes = [LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS];
let index = 0;
currMode = shapeModes[index];
let helpText = createP("Click on the button to change the beginShape() mode");
helpText.position(20, 0);
let closeBtn = createButton("Change mode");
closeBtn.position(20, 40);
closeBtn.mouseClicked(() => {
if (index < shapeModes.length) index++;
else index = 0;
currMode = shapeModes[index];
});
}
function draw() {
clear();
// Starting the shape using beginShape()
beginShape(currMode);
// Specifying all the vertices
vertex(45, 245);
vertex(100, 75);
vertex(245, 245);
vertex(15, 150);
vertex(250, 125);
// Ending the shape using endShape()
endShape();
// Points for demonstration
circle(45, 245, 10);
circle(100, 75, 10);
circle(245, 245, 10);
circle(15, 150, 10);
circle(250, 125, 10);
}
输出:
示例 2:
let vertices = [];
function setup() {
createCanvas(500, 300);
textSize(18);
text("Click anywhere to place a vertice at that point", 10, 20);
}
function mouseClicked() {
// Update the vertices array with
// current mouse position
vertices.push({ x: mouseX, y: mouseY });
clear();
text("Click anywhere to place a vertice at that point", 10, 20);
// Start the shape using beginShape()
beginShape();
// Use the vertices in the array
// with the vertex() function
for (let i = 0; i < vertices.length; i++)
vertex(vertices[i].x, vertices[i].y);
// End the shape using endShape()
endShape();
// Draw a circle at the last drawn vertice
// for demonstration
circle(mouseX, mouseY, 15);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5/beginShape