Wireframe Toggle

Toggle a torus material between solid and wireframe. Use the GUI toggle or press W.

What this code does

  • Geometry: Builds a TorusGeometry with tube radius 0.3 and ring radius 0.8.
  • Material: Uses MeshStandardMaterial; its wireframe boolean draws only edges when true.
  • Lighting: A directional light at (2,2,2) produces shaded faces to compare with wireframe view.
  • Controls: OrbitControls for orbiting; a keyboard handler toggles on W.
  • GUI: A lil-gui checkbox mirrors and updates material.wireframe.
  • Animation: Rotates the torus slightly each frame and renders the scene.

JavaScript (plain)

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)
camera.position.z = 3
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)

document.querySelector('#app').appendChild(renderer.domElement)

const torus = new THREE.Mesh(
  new THREE.TorusGeometry(0.8, 0.3, 32, 64),
  new THREE.MeshStandardMaterial({ color: 0x9bdc6e })
)
scene.add(torus)

// light for shading
const light = new THREE.DirectionalLight(0xffffff, 1)
light.position.set(2, 2, 2)
scene.add(light)

// toggle wireframe with the "w" key
window.addEventListener('keydown', (e) => {
  if (e.key.toLowerCase() === 'w') {
    torus.material.wireframe = !torus.material.wireframe
  }
})

// alternatively, a checkbox UI:
// const input = Object.assign(document.createElement('input'), { type: 'checkbox' })
// input.addEventListener('change', (e) => { torus.material.wireframe = e.target.checked })
// document.body.appendChild(input)

function animate () {
  requestAnimationFrame(animate)
  torus.rotation.x += 0.01
  torus.rotation.y += 0.01
  renderer.render(scene, camera)
}
animate()