
点赞 + 关注 + 收藏 = 学会了
cylinder() 是 p5.js 中用于绘制3D 圆柱体的函数。圆柱体由顶部、底部两个圆形和侧面组成,所有表面由三角形拼接而成(这是 3D 绘图的常见方式)。
注意:cylinder() 只能在「WebGL 模式」下使用(WebGL 是浏览器的 3D 绘图技术),普通 2D 模式下无法生效。
cylinder() 的参数非常灵活,所有参数都是可选的,按顺序传入即可:
cylinder([radius], [height], [detailX], [detailY], [bottomCap], [topCap])true 绘制,false 不绘制)。true(默认绘制底部)。true 绘制,false 不绘制)。true(默认绘制顶部)。一个半径 50、高度 50、边缘平滑(detailX=24)、带上下底的圆柱体。

function setup() {
createCanvas(200, 200, WEBGL); // 开启 WebGL 模式(必须)
describe('灰色背景上的白色圆柱体');
}
function draw() {
background(200); // 灰色背景
orbitControl(); // 允许鼠标拖动旋转视角(3D 必备)
cylinder(); // 不填参数,用默认值
}createCanvas 第三个参数 WEBGL 是 3D 绘图的开关;orbitControl() 让你能拖动鼠标 360° 查看圆柱体。
半径 30,高度默认等于半径(也是 30)的圆柱体。

// 其他代码和示例 1 相同,仅修改 cylinder() 部分
cylinder(30); // 只传 radius=30只传一个参数时,默认是 radius,height 会自动等于它。
半径 30、高度 50 的圆柱体(更 “瘦长”)。

cylinder(30, 50); // radius=30,height=50顶部和底部只有 5 条边,看起来像一个 “五角柱”(接近盒子)。
detailX 越小,形状越 “棱角分明”;越大越接近圆形。

cylinder(30, 50, 6); // detailX=6侧面沿高度方向分成 2 段,比默认(detailY=1)更平滑。

cylinder(30, 50, 24, 2); // detailX=24(默认圆),detailY=2
cylinder(30, 50, 24, 1, false); // bottomCap=false只剩侧面,像一个 “圆筒”(比如水管)。

cylinder(30, 50, 24, 1, false, false); // 两个都设为 false加入颜色和旋转效果。

function setup() {
createCanvas(400, 400, WEBGL); // 更大的画布
describe('会旋转的彩色圆柱体');
}
function draw() {
background(25); // 深色背景
orbitControl(); // 允许鼠标旋转
// 设置颜色(RGB 模式:红、绿、蓝)
fill(100, 200, 255); // 浅蓝色
// 让圆柱体旋转(随时间变化角度)
rotateX(frameCount * 0.01); // 绕 x 轴旋转
rotateY(frameCount * 0.02); // 绕 y 轴旋转
// 绘制圆柱体:半径 60,高度 120,较圆(detailX=16),侧面平滑(detailY=3)
cylinder(60, 120, 16, 3);
}以上就是本文的全部内容啦,想了解更多 P5.js 用法欢迎关注 《P5.js中文教程》。
点赞 + 关注 + 收藏 = 学会了