Copy a mesh in threejs

The process of copying an object in javaScript can be tricky business, as such I have wrote a few posts on this when it comes to cloning objects with lodash methods as well as native javaScript by itself. However if I am making a threejs project and I want to copy a mesh object then I just need to use the clone method of a mesh instance.

So then this will be a quick post on the mesh clone method in threejs that can be used as a way to create copies of a mesh object in threejs.

1 - Mesh copy basic example

To copy a mesh in threejs all I need to do is just call the clone method of a mesh object instance, and what will be returned is a copy of that mesh. Here I have a simple example where I am creating an original mesh with the THREE.Mesh constructor, and then creating a bunch of copies with the clone method of the Mesh instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// SCENE
var scene = new THREE.Scene();
// CAMERA
var camera = new THREE.PerspectiveCamera(40, 16 / 9, 0.1, 1000);
camera.position.set(6, 6, 6);
camera.lookAt(0, 0, 0);
// RENDER
var renderer = new THREE.WebGLRenderer();
document.getElementById('demo').appendChild(renderer.domElement);
renderer.setSize(360, 180);
// MESH
var original = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshNormalMaterial());
scene.add(original);
// Copy the mesh a bunch of times
var i = 0, mesh, rad, x, z;
while (i < 10) {
mesh = original.clone();
rad = Math.PI * 2 * (i / 10);
x = Math.cos(rad) * 3;
z = Math.sin(rad) * 3;
mesh.position.set(x, 0, z);
scene.add(mesh);
i += 1;
}
renderer.render(scene, camera);