Rahul Sharma Rahul Sharma - 7 days ago 5
Javascript Question

three js custom geometry

I am trying to learn threeJS to build a 3D webapp in which I need custom 3D geometrical shapes. I found the code of how doing this.
But the browser doesn't show anything when I open my html file.

Here is my code:

<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="Three.js"></script>
<script src="Detector.js"></script>
<script src="three.min.js"></script>
<script defer="defer">
// revolutions per second
var angularSpeed = 0.2;
var lastTime = 0;

// this function is executed on each animation frame
function animate(){
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
//geom.rotation.y += angleChange;
lastTime = time;

// render
renderer.render(scene, camera);

// request new frame
requestAnimationFrame(function(){
animate();
});
}

// renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// camera
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 500;

// scene
var scene = new THREE.Scene();

var geom = new THREE.Geometry();
var v1 = new THREE.Vector3(-10,10,0);
var v2 = new THREE.Vector3(10,10,0);
var v3 = new THREE.Vector3(10,-10,0);

geom.vertices.push(new THREE.Vertex(v1));
geom.vertices.push(new THREE.Vertex(v2));
geom.vertices.push(new THREE.Vertex(v3));

geom.faces.push( new THREE.Face3(0, 1, 2));
geom.computeFaceNormals();

var object = new THREE.Mesh( geom, new THREE.MeshNormalMaterial() );
//object.doubleSided = true;
object.overdraw = true;
scene.addObject(object);

animate();
</script>
</body>
</html>


Please tell me if there is something wrong in the code.

Answer

There might be multiple error. You might want to check your console. Some error sources could be:

  1. There is no THREE.Vertex. This has been replaced by THREE.Vector. See the Migration page. So you should just use geom.vertices.push(v1)

  2. Again, see Migration page. It's scene.add() instead of scene.addObject()

Finally, wrapping animate in another function for requestAnimationFrame is redundant. You can directly pass the animate function object: requestAnimationFrame(animate)

Comments