Files
uni/year4/semester1/CT404: Graphics & Image Processing/materials/week2/examples/Threejs-5-partial-desk-lamp.html

81 lines
2.8 KiB
HTML

<html>
<head>
<script src="three.js"></script>
<script>
'use strict'
function draw() {
// create renderer attached to HTML Canvas object
var c = document.getElementById("canvas");
var renderer = new THREE.WebGLRenderer({ canvas: c, antialias: true });
// create the scenegraph
var scene = new THREE.Scene();
// create a camera
var fov = 75;
var aspect = 600/600;
var near = 0.1;
var far = 1000;
var camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
camera.position.set(0, 1.5, 6);
// add a light to the scene
var light = new THREE.PointLight(0xFFFFFF);
light.position.set(0, 10, 30);
scene.add(light);
// desk lamp base
// args: radiusTop, radiusBottom, height, radialSegments
var base = new THREE.Mesh(
new THREE.CylinderBufferGeometry(1, 1, 0.1, 12),
new THREE.MeshLambertMaterial({color: 0xAAAAAA}) );
scene.add(base);
// desk lamp first arm piece
var arm = new THREE.Mesh(
new THREE.CylinderBufferGeometry(0.1, 0.1, 3, 12),
new THREE.MeshLambertMaterial({color: 0xAAAAAA}) );
// since we want to rotate around a point other than the arm's centre,
// we can create a pivot point as the parent of the arm, position the
// arm relative to that pivot point, and apply rotation on the pivot point
var pivot = new THREE.Object3D();
// centre of rotation we want
// (in world coordinates, since pivot is not yet a child of the base)
pivot.position.set(0, 0, 0);
pivot.add(arm); // pivot is parent of arm
base.add(pivot); // base is parent of pivot
// translate arm relative to its parent, i.e. 'pivot'
arm.position.set(0, 1.5, 0);
// rotate pivot point relative to its parent, i.e. 'base'
pivot.rotateOnAxis(new THREE.Vector3(0,0,1), -Math.PI/6);
// clone a second arm piece (consisting of a pivot with a cylinder as its child)
var pivot2 = pivot.clone();
// add as a child of the 1st pivot
pivot.add(pivot2);
// rotate the 2nd pivot relative to the 1st pivot (since it's nested)
pivot2.rotation.z = Math.PI/3;
// translate the 2nd pivot relative to the 1st pivot
pivot2.position.set(0,3,0);
// TEST: we can rotate the 1st arm piece and the 2nd arm piece should stay correct
pivot.rotateOnAxis(new THREE.Vector3(0,0,1), Math.PI/12);
// TEST: we can also move the base, and everything stays correct
base.position.x -= 3;
// render the scene as seen by the camera
renderer.render(scene, camera);
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="600" height="600"></canvas>
</body>
</html>