What are DragControls in three.js?
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.
Constructor
Here's the syntax to initialize DragControls:
const controls = new DragControls(objects, camera, renderer.domElement);
Parameters
The constructor for DragControls takes the following parameters:
objects: This is the array ofObject3Dthat theDragControlswork for.camera: This is theTHREE.Cameraobject placed to view our scene.renderer.domElement: This is the HTML canvas in which our scene is being rendered. ThedomElementproperty of therenderercontains the canvas.
Return value
The constructor returns an object that is the child of the EventDispatcher class.
Example
In the example shown above, the user is able to drag and drop the sphere inside the scene.
Explanation
In the code shown above, we first created a scene in three.js.
Lines 52–55: We initialize the
objects, an array, and a pushshape.Line 58: We initialize our
DragControlsand store the returned object insidecontrols. We pass theobjectsarray along with thecameraand the HTML canvas.Lines 68–70: We add an event listener to listen for the
dragstartevent. 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
dragendevent. 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