Check out this interactive demo where the camera zooms out when you click a button.
JS Fiddle Demo
// Set up variables for camera, scene, renderer, controls, and cubeMesh
document.querySelector('button').onclick = function () {
let x = cubeMesh.position.x;
let y = cubeMesh.position.y;
let z = cubeMesh.position.z;
// Adjust camera position
camera.position.x = 0;
camera.position.y = y + 200;
camera.position.z = z + 100;
camera.lookAt(controls.target);
};
// Initialize lights in the scene
var initLights = function () {
// Add directional and ambient lighting
var light1 = new THREE.DirectionalLight(0xffffff);
light1.position.set(1, 1, 1);
scene.add(light1);
var light2 = new THREE.DirectionalLight(0x002288);
light2.position.set(-1, -1, -1);
scene.add(light2);
var light3 = new THREE.AmbientLight(0x222222);
scene.add(light3);
};
// Main initialization function
var init = function () {
// Set up renderer, camera, and scene
renderer = new THREE.WebGLRenderer({antialias: false});
renderer.setSize(window.innerWidth, window.innerHeight);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 300;
scene = new THREE.Scene();
// Set up trackball controls
controls = new THREE.TrackballControls(camera);
controls.target.set(0, 0, 0);
controls.rotateSpeed = 2;
document.body.appendChild(renderer.domElement);
// Create sphere and cube meshes
var sphereGeom = new THREE.SphereGeometry(100, 32, 32);
var sphereMat = new THREE.MeshPhongMaterial({
color: 0xfb3550,
flatShading: true
});
var sphereMesh = new THREE.Mesh(sphereGeom, sphereMat);
var cubeDim = 20;
var cubeGeom = new THREE.BoxGeometry(cubeDim, cubeDim, cubeDim);
var cubeMat = new THREE.MeshPhongMaterial({
color: 0x7cf93e,
flatShading: true
});
cubeMesh = new THREE.Mesh(cubeGeom, cubeMat);
// Position and rotate cube mesh
var spherical = new THREE.Spherical();
spherical.set(100 + cubeDim / 2, 0.4, 0);
cubeMesh.position.setFromSpherical(spherical);
var zero = new THREE.Vector3(0, 0, 0);
cubeMesh.lookAt(zero);
// Add meshes to the scene
scene.add(sphereMesh);
sphereMesh.add(cubeMesh);
initLights();
};
// Render function
var render = function () {
console.log(camera.position);
renderer.render(scene, camera);
};
// Animation loop
var animate = function () {
requestAnimationFrame(animate);
controls.update();
render();
};
init();
animate();