Three.js Drag & Drop Scene Builder
Build a scene in Three.js by dragging assets from an HTML palette onto the ground, with a live ghost preview, grid snapping, drag-to-move, 45° rotation and delete shortcuts, shadows and placement stats.
Key topics: three.js drag and drop, scene editor, level editor, grid snap, raycasting, html5 drag
Game Over
What this code does
- HTML5 Drag: palette items set the asset type in `dataTransfer`, and the canvas accepts the drop.
- Ground Projection: the pointer ray intersects an analytic ground `Plane`, which is cheaper than meshes and never misses.
- Ghost Preview: during dragover a translucent copy follows the snapped drop point.
- Moving: pressing on a placed object picks its root group, which then slides along the ground plane.
- Editing: R rotates by 45°, Delete removes the selection, and a box helper outlines what is selected.
- Assets: crates, trees, rocks, benches and lamps (with real point lights) are built from primitives.
- Controls: grid snap, grid size and clear scene.
Related Demos
Continue Learning
JavaScript Implementation
// HTML5 drag-and-drop from a DOM palette onto the ground plane
const ground = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)
const raycaster = new THREE.Raycaster()
paletteItem.draggable = true
paletteItem.addEventListener('dragstart', (e) => e.dataTransfer.setData('text/plain', 'Crate'))
renderer.domElement.addEventListener('dragover', (e) => e.preventDefault()) // allow dropping
renderer.domElement.addEventListener('drop', (e) => {
e.preventDefault()
const rect = renderer.domElement.getBoundingClientRect()
const ndc = new THREE.Vector2((e.clientX - rect.left) / rect.width * 2 - 1, -(e.clientY - rect.top) / rect.height * 2 + 1)
raycaster.setFromCamera(ndc, camera)
const point = raycaster.ray.intersectPlane(ground, new THREE.Vector3())
point.set(Math.round(point.x * 2) / 2, 0, Math.round(point.z * 2) / 2) // snap to a 0.5 grid
scene.add(makeAsset(e.dataTransfer.getData('text/plain')).translateX(point.x).translateZ(point.z))
})