How to remove the child of an Object3D in three.js
We can use two methods to remove the child of an Object3D class object which is present inside the three.js scene graph:
The
remove()methodThe
removeFromParent()method
Syntax
The remove() method
This method is invoked through the parent object.
parentObject.remove(childObject);
Parameters
This method takes the Object3D to be removed as a parameter. Here,
parentObject: This is the parent whose child we want to remove.childObject: This is the child that we want to remove.
Note: The
childObjectmust already be a child ofparentObjectbefore it is removed. If it is not already a child, no effect takes place.
TheremoveFromParent() method
This method is invoked through the child itself.
childObject.removeFromParent();
Parameters
-
This method does not take any parameters.
-
childObject: This is the child who is to be removed from its parent.
Code example
We'll demonstrate the removal of a child with the help of an example:
Code explanation
In the code shown above, we create a scene in three.js. Here, shape_one is the square and is the parent of the two spheres. The green sphere is shape_two and the red one is shape_three.
Lines 47 & 48: We added
shape_twoandshape_threetoshape_oneas children.
The scene graph of the code shown above looks something like the illustration shown below:
Removing a child from the parent object will make the scene graph look the following illustration:
This will prevent shape_two from being rendered entirely as it is no longer a part of the scene.
Here,
Line 58: We remove
shape_twofrom the children ofshape_oneusingremove()and can observe that it is no longer a part of the scene.Line 61: We can uncomment this line and comment Line 58 to observe the same effect of
removeFromParent()method as well.
Free Resources