JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
JavaScript
var camera, scene, renderer;
var geometry, material, mesh, light;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
mesh.castShadow = true;
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
document.body.appendChild( renderer.domElement );
var floor = new THREE.Mesh(
new THREE.PlaneBufferGeometry( 10, 10 ),
new THREE.ShadowMaterial({ color: "red" })
);
floor.position.y = -0.5;
floor.rotation.x = -0.5 * Math.PI;
floor.receiveShadow = true;
scene.add(floor);
light = new THREE.DirectionalLight();
light.position.set( -0.2, 0.6, 0.2 );
light.castShadow = true;
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 500;
light.shadow.camera.left = -0.2;
light.shadow.camera.right = 0.2;
light.shadow.camera.top = 0.2;
light.shadow.camera.bottom = -0.2;
scene.add( light );
scene.add( new THREE.CameraHelper( light.shadow.camera ) );
// follow the mesh
light.target = mesh;
}
function animate() {
requestAnimationFrame( animate );
var t = 2 * Math.PI * (Date.now() % 10000) * 0.0001;
mesh.position.x = Math.sin (t);
// follow the mesh
light.position.x = mesh.position.x;
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}