three.js Arcball Controls Camera Animation
by kimalbrecht
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://raw.githack.com/mrdoob/three.js/dev/build/three.module.js",
"three/addons/": "https://raw.githack.com/mrdoob/three.js/dev/examples/jsm/"
}
}
</script>
CSS
body {
margin: 0px;
}
JavaScript
// Simple three.js example
import * as THREE from 'three';
import { ArcballControls } from 'three/addons/controls/ArcballControls.js';
let mesh, renderer, scene, camera, controls;
init();
animate();
function init() {
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setPixelRatio( window.devicePixelRatio );
document.body.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 20, 20, 20 );
// controls
controls = new ArcballControls( camera, renderer.domElement, scene );
controls.cursorZoom = true;
controls.enablePan = true;
controls.enableRotate = false;
controls.setMouseAction('PAN', 0);
controls.setMouseAction('PAN', 1);
controls.setMouseAction('PAN', 2);
// ambient
scene.add( new THREE.AmbientLight( 0x222222 ) );
// light
const light = new THREE.DirectionalLight( 0xffffff, 1 );
light.position.set( 20,20, 0 );
scene.add( light );
// axes
scene.add( new THREE.AxesHelper( 20 ) );
// geometry
const geometry = new THREE.SphereGeometry( 5, 12, 8 );
// material
const material = new THREE.MeshPhongMaterial( {
color: 0x00ffff,
flatShading: true,
transparent: true,
opacity: 0.7,
} );
// mesh
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
}
function animate() {
requestAnimationFrame( animate );
//controls.update();
renderer.render( scene, camera );
}
controls.addEventListener( 'change', function () {
renderer.render( scene, camera );
} );
function animateCamera () {
gsap.to( camera.position, {
duration: 1,
x: Math.random()*10,
y: Math.random()*10,
z: 20,
onUpdate: function() {
animate();
...