Creating a rounded rectangle in Three.js involves defining a custom shape using the THREE.Shape class and then generating a mesh from it. This approach allows for precise control over the geometry, enabling features like rounded corners similar to CSS’s border-radius. (Plane mesh with rounded corners that can have an image texture)
Step-by-Step Guide to Creating a Rounded Rectangle in Three.js
- Define the Rounded Rectangle Shape: Use the
THREE.Shapeclass to create a path that outlines a rectangle with rounded corners. This is achieved by combining straight lines and quadratic curves.
const width = 2; const height = 1; const radius = 0.2; const shape = new THREE.Shape(); shape.moveTo(0, radius); shape.lineTo(0, height - radius); shape.quadraticCurveTo(0, height, radius, height); shape.lineTo(width - radius, height); shape.quadraticCurveTo(width, height, width, height - radius); shape.lineTo(width, radius); shape.quadraticCurveTo(width, 0, width - radius, 0); shape.lineTo(radius, 0); shape.quadraticCurveTo(0, 0, 0, radius);
- This code creates a 2D shape with specified width, height, and corner radius.
- Create Geometry from the Shape: Convert the defined shape into geometry using
THREE.ShapeGeometry.
const geometry = new THREE.ShapeGeometry(shape);
- Create a Mesh and Add It to the Scene: Apply a material to the geometry and add the resulting mesh to your Three.js scene.
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);