Three.js Molecule Viewer (PDB Ball-and-Stick)
Three.js molecular viewer with a PDB parser, automatic covalent-radius bond detection, CPK coloring and ball-and-stick, space-filling and stick styles, with built-in molecules from water to C₆₀ and an α-helix.
Key topics: three.js molecule viewer, pdb viewer, ball and stick, cpk colors, chemistry, fullerene, protein structure
Game Over
What this code does
- PDB Parsing: ATOM/HETATM records are read from fixed columns (x 31–38, y 39–46, z 47–54, element 77–78).
- Bond Inference: atoms closer than 1.2 × the sum of their covalent radii are bonded, found in O(n) with a spatial hash.
- Rendering Styles: ball-and-stick uses scaled van der Waals radii, space-filling uses full vdW spheres, and sticks use capped cylinders.
- Half Bonds: each bond is two instanced cylinders colored by its own atom, the classic CPK look.
- Built-in Data: C₆₀ is generated from truncated-icosahedron vertices, and the helix from ideal α-helix parameters.
- Controls: molecule, style, atom scale, spin, and "Load .pdb file…" for your own structures (read locally, never uploaded).
Related Demos
Continue Learning
JavaScript Implementation
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 200)
camera.position.set(0, 1, 9)
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)
document.querySelector('#app').appendChild(renderer.domElement)
scene.add(new THREE.HemisphereLight(0xffffff, 0x334155, 1.3))
// Parse ATOM/HETATM records from a PDB string (fixed-width columns)
function parsePdb (text) {
return text.split('\n')
.filter(l => l.startsWith('ATOM') || l.startsWith('HETATM'))
.map(l => ({
el: l.slice(76, 78).trim() || l.slice(12, 16).trim()[0],
p: new THREE.Vector3(+l.slice(30, 38), +l.slice(38, 46), +l.slice(46, 54))
}))
}
const colors = { H: 0xf8fafc, C: 0x4b5563, N: 0x3b82f6, O: 0xef4444 }
const covalent = { H: 0.31, C: 0.76, N: 0.71, O: 0.66 }
const atoms = parsePdb(pdbText)
atoms.forEach(a => {
const mesh = new THREE.Mesh(new THREE.SphereGeometry(0.4, 24, 16), new THREE.MeshStandardMaterial({ color: colors[a.el] }))
mesh.position.copy(a.p)
scene.add(mesh)
})
// Bond any two atoms closer than the sum of their covalent radii (+20%)
for (let i = 0; i < atoms.length; i++) {
for (let j = i + 1; j < atoms.length; j++) {
const d = atoms[i].p.distanceTo(atoms[j].p)
if (d < (covalent[atoms[i].el] + covalent[atoms[j].el]) * 1.2) {
const bond = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, d, 10), new THREE.MeshStandardMaterial({ color: 0x9ca3af }))
bond.position.copy(atoms[i].p).lerp(atoms[j].p, 0.5)
bond.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), atoms[j].p.clone().sub(atoms[i].p).normalize())
scene.add(bond)
}
}
}
renderer.render(scene, camera)