Drawing 3D Cylinders in p5.js with cylinder()

cylinder() is a built-in function in p5.js for rendering 3D cylinders. The geometry consists of two circular caps (top and bottom) and a curved lateral surface, all constructed from triangular faces—a standard approach in 3D graphics.

Important: This function only works when the canvas is initialized in WebGL mode. Attempting to use it in the default 2D renderer will have no effect.

Function Signature

cylinder([radius], [height], [detailX], [detailY], [includeBottom], [includeTop])
  • radius (Number, default: 50) – Radius of both circular ends.
  • height (Number, default: radius) – Distance between top and bottom along the Y-axis.
  • detailX (Integer, default: 24) – Number of segments around the circumference. Lower values produce polygonal shapes (e.g., 4 yields a square prism); higher values approximate a smooth circle.
  • detailY (Integer, default: 1) – Number of vertical subdivisions along the height. Increasing this value adds more rows of triangles, improving curvature smoothness.
  • includeBottom (Boolean, default: true) – Whether to rander the bottom cap.
  • includeTop (Boolean, default: true) – Whether to render the top cap.

Basic Examples

Default Cylinder

Renders a cylinder with radius = 50, height = 50, smooth sides (detailX=24), and both caps visible.

function setup() {
  createCanvas(200, 200, WEBGL);
}

function draw() {
  background(200);
  orbitControl();
  cylinder();
}

Custom Radius

Sets radius to 30; height defaults to match it.

cylinder(30);

Custom Radius and Height

Creates a taller, narrower shape.

cylinder(30, 50);

Low Polygon Count

Uses only 6 segments around the base, resulting in a hexagonal prism.

cylinder(30, 50, 6);

Increased Vertical Detail

Adds an extra row of triangles along the height for smoother shading.

cylinder(30, 50, 24, 2);

Open Bottom

Hides the bottom face while keeping the top.

cylinder(30, 50, 24, 1, false);

Hollow Tube

Disables both caps, leaving only the lateral surface.

cylinder(30, 50, 24, 1, false, false);

Animated Colored Cylinder

Applies color and continuous rotation for dynamic visualization.

function setup() {
  createCanvas(400, 400, WEBGL);
}

function draw() {
  background(25);
  orbitControl();
  
  fill(100, 200, 255);
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.02);
  
  cylinder(60, 120, 16, 3);
}

Tags: p5.js WebGL 3D Graphics cylinder creative coding

Posted on Mon, 25 May 2026 21:51:53 +0000 by iacataca