Three.js is a JavaScript library that is built on top of WebGL and is used to render animations on the web.
We have the option to introduce user controls in a three.js scene to add more interactivity to our project. There are multiple types of controls that three.js offers. In this Answer, we focus on DragControls
, which allow the user to drag and drop 3D objects in the scene.
Here's the syntax to initialize DragControls
:
const controls = new DragControls(objects, camera, renderer.domElement);
The constructor for DragControls
takes the following parameters:
objects
: This is the array of Object3D
that the DragControls
work for.
camera
: This is the THREE.Camera
object placed to view our scene.
renderer.domElement
: This is the HTML canvas in which our scene is being rendered. The domElement
property of the renderer
contains the canvas.
The constructor returns an object that is the child of the EventDispatcher
class.
In the example shown above, the user is able to drag and drop the sphere inside the scene.
In the code shown above, we first created a scene in three.js.
Lines 52–55: We initialize the objects
, an array, and a push shape
.
Line 58: We initialize our DragControls
and store the returned object inside controls
. We pass the objects
array along with the camera
and the HTML canvas.
Lines 68–70: We add an event listener to listen for the dragstart
event. This is when the user starts to drag the object. When the event is triggered, we set the color of the object being dragged to a lighter shade of red.
Lines 72–74: We add another event listener that listens for the dragend
event. This is when the user releases the object. We set the color of the object back to a darker shade of red inside the event handler.
Note: After the drag ends, the color of the shape is permanently changed to red.
Free Resources