Three.js 3D Function Plotter (z = f(x, y, t))

Type any expression and plot z = f(x, y, t) as an animated 3D surface in Three.js, with a safe built-in expression parser, height-based color ramp, contour lines and classic presets like Peaks and the monkey saddle.

Key topics: three.js function plot, 3d graph, surface plot, math visualization, contour lines, expression parser

What this code does

- Expression Compiler: a small recursive-descent parser turns text into closures, with no `eval` (operators + − × ÷ ^, x, y, t, π, e, sin, exp, log…).
- Surface Mesh: a rotated `PlaneGeometry` is resampled every frame when the expression uses `t`, with normals recomputed for lighting.
- Color Ramp: vertex colors follow a viridis-style ramp from the minimum to the maximum height.
- Contour Lines: `onBeforeCompile` adds anti-aliased iso-height lines to `MeshStandardMaterial` using `fwidth`.
- Wire Overlay: a coarser `WireframeGeometry` floats over the surface to show the grid structure.
- Controls: expression, presets, domain, height scale, resolution, animation, wire overlay and contours.

Continue Learning

JavaScript Implementation

ES6+
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 200)
camera.position.set(11, 9, 11)
camera.lookAt(0, 0, 0)
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)
document.querySelector('#app').appendChild(renderer.domElement)
scene.add(new THREE.HemisphereLight(0xffffff, 0x223344, 1.2))

const f = (x, y, t) => Math.sin(2 * Math.hypot(x, y) - 2 * t) / (1 + 0.3 * Math.hypot(x, y))
const geometry = new THREE.PlaneGeometry(10, 10, 140, 140).rotateX(-Math.PI / 2)
geometry.setAttribute('color', new THREE.BufferAttribute(new Float32Array(geometry.attributes.position.count * 3), 3))
const surface = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ vertexColors: true, side: THREE.DoubleSide }))
scene.add(surface)

const color = new THREE.Color()

function animate (time) {
  requestAnimationFrame(animate)
  const t = time / 1000
  const pos = geometry.attributes.position
  for (let i = 0; i < pos.count; i++) {
    const z = f(pos.getX(i) * 0.6, pos.getZ(i) * 0.6, t)
    pos.setY(i, z)
    color.setHSL(0.7 - (z + 1) * 0.3, 0.8, 0.5)
    geometry.attributes.color.setXYZ(i, color.r, color.g, color.b)
  }
  pos.needsUpdate = true
  geometry.attributes.color.needsUpdate = true
  geometry.computeVertexNormals()
  renderer.render(scene, camera)
}
animate(0)